Python忽略了循环中的if语句

时间:2016-11-15 21:52:52

标签: python loops if-statement

我尝试做一个循环,要求用户选择一个字符串,将其转换为整数,然后计算总数并继续询问,直到用户输入q进行退出。除了我的if语句完全被Python忽略之外,一切顺利。任何人都可以帮助我吗?

到目前为止我的代码看起来像这样:

l = 0.89
g = 2.50
p = 0.50
t = 0.75
o = 0.50
Subtotal = 0
Total = 0
q = ""
quanity = 0
choice = ""

choice = input('L - Lettuce \nG - Green Beans \nP - Peppers \nT - Tomatoes \nO - Onions \nS - Seasonal Item \nQ - Quit')

while choice != q:
   Subtotal = 0
   quanity = 0
   quanity = input('How Many?')
   if choice == l:
      choice = 0.89
   elif choice == g:
      choice = 2.50
   elif choice == p:
      choice = 0.50
   elif choice == t:
      choice = 0.75
   elif choice == o:
      choice = 0.50
   Subtotal = choice * quanity
   Total = Total + Subtotal
   print('Your total so far is $' ,Total)
   choice = ""
   choice = input('L - Lettuce \nG - Green Beans \nP - Peppers \nT - Tomatoes \nO - Onions \nS - Seasonal Item \nQ - Quit')
print('All Done')

2 个答案:

答案 0 :(得分:3)

您正在针对包含str值的变量对来自input的{​​{1}}进行测试。当然没什么打。让测试检查如下:

float

请注意,一个更简洁的解决方案是定义从字母到值的映射,因此您不会使用那么多链式比较:

choice = choice.upper()
if choice == 'L':
    choice = l
elif choice == 'G':
    choice = g

答案 1 :(得分:0)

l = 0.89
g = 2.50
p = 0.50
t = 0.75
o = 0.50
Subtotal = 0
Total = 0
q = ""
quanity = 0
choice = ""

choice = input('L - Lettuce \nG - Green Beans \nP - Peppers \nT - Tomatoes \nO - Onions \nS - Seasonal Item \nQ - Quit')

while choice != 'q':
   Subtotal = 0
   quanity = 0
   quanity = float(input('How Many?'))
   if choice == 'l':
      choice = 0.89
   elif choice == 'g':
      choice = 2.50
   elif choice == 'p':
      choice = 0.50
   elif choice == 't':
      choice = 0.75
   elif choice == 'o':
      choice = 0.50
   Subtotal = choice * quanity
   Total = Total + Subtotal
   print('Your total so far is $' ,Total)
   choice = ""
   choice = input('L - Lettuce \nG - Green Beans \nP - Peppers \nT - Tomatoes \nO - Onions \nS - Seasonal Item \nQ - Quit')
print('All Done')

您需要在输入之前添加float,因为input()会在python 3.x中返回一个字符串。 您还需要比较字符串if choice == 'string':