这个循环有什么问题?继续在这里不工作

时间:2018-12-21 02:44:14

标签: python

blueberries=0
raspberries=0
while raspberries>-1:
    print('Enter a number for blueberries:')
    raspberries=float(input('Enter a number'))
    print('Enter a nuumber for raspberries:')
    blueberries=float(input('Enter a number'))
    if raspberries==0:
        continue
    print(blueberries+raspberries)

在这里我已经尝试了多次

1 个答案:

答案 0 :(得分:1)

您混合了blueberriesraspberries变量:

print("Enter a number for blueberries:")
raspberries=float(input("Enter number"))  # should have stored in blueberries
print("Enter # raspberries:")
blueberries=float(input("Enter number"))  # should have stored in raspberries

这就是为什么当您输入47时将其存储在raspberries中的原因。 因此if raspberries==0将为False。

您只需要存储正确的变量即可:

>>> blueberries=0
>>> raspberries=0
>>> while raspberries>-1:
...   print("Enter a number for blueberries:")
...   blueberries=float(input("Enter number "))
...   print("Enter a number for raspberries:")
...   raspberries=float(input("Enter number "))
...   if raspberries==0:
...     continue
...   print(blueberries+raspberries)
... 
Enter a number for blueberries:
Enter number 40
Enter a number for raspberries:
Enter number 5
45.0
Enter a number for blueberries:
Enter number 47
Enter a number for raspberries:
Enter number 0          
Enter a number for blueberries:   # continued here, did not print
Enter number

您实际上可以简化多个print

blueberries=0
raspberries=0
while raspberries>-1:
    blueberries=float(input("Enter number of blueberries: "))
    raspberries=float(input("Enter number of raspberries: "))
    if raspberries==0:
        continue
    print(blueberries + raspberries)

最后,您可能要寻找的不是continue,而是break,如果raspberries==0,它将退出循环。

blueberries=0
raspberries=0
while raspberries>-1:
    blueberries=float(input("Enter number of blueberries: "))
    raspberries=float(input("Enter number of raspberries: "))
    if raspberries==0:
        break
    print(blueberries + raspberries)