Python Forum

Full Version: Calculator code issue using list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The problem is that when I choose / and input 5 and 0 (2nd number as 0) it is giving 0.0 but not printing the divisior is zero


#!/usr/bin/python3
num=input("please select operator +,-,*,/ or q to quit")
while num != 'q':
   numlist=input("please enter at least 2 numbers ").split()
   numlist=[float(i) for i in numlist]
   total = numlist[0]
   del numlist[0]
   if num == '+':
      for i in numlist:
         total = i + total
      print (total)
   elif num == '-':
      for i in numlist:
         total = i - total
      print (total)
   elif num == '*':
      for i in numlist:
         total = i * total
      print (total)
   elif num =='/':
      if i in numlist ==0:
         print ("divisior is zero")
      else:
         for i in numlist:
            total = i / total
         print (total)
   num=input("please select operator +,-,*,/ or q to quit")
I think you need line 21 to be:
if 0 in numlist:
Thank you that helped but can you explain why cant we substiute i because i can be any number in list
(Jun-11-2021, 10:01 PM)topfox Wrote: [ -> ]I think you need line 21 to be:
if 0 in numlist:
The line
if i in numlist ==0:
will give NameError: name 'i' is not defined
if i was defined it would return True if i was in numlist and then do a comparison of True == 0 which would be False
If you want to check if something is in a list just do
numlist = [5, 0]
print(0 in numlist)
Output:
True

(Jun-11-2021, 10:04 PM)kirt6405 Wrote: [ -> ]Thank you that helped but can you explain why cant we substiute i because i can be any number in list
You are not for looping to give i a value like in the other elif statements.
I believe that i is not defined at line 21, and I'm not quite sure what you are trying to do.

i could be used instead of 0, if a value had been assigned to it, like this:

i = 0
if i in numlist
the expression '0 in numlist' is evaluated as True if the value 0 matches any item in the list numlist.
the expression 'i in numlist == 0' would I suppose be evaluated as True if 'i in numlist' evaluated as False. Then 'False == 0' would be True. That means the expression 'i in numlist == 0' is equivalent to 'i not in numlist', hence you may get the opposite answer to what you expect.
I hope that makes sense!