Python 帮助进行while循环
在下面的代码中,我希望计数器保持在0,而不是在一只股票达到0时进入负数,这将继续向下计数其他项目Python 帮助进行while循环,python,loops,while-loop,Python,Loops,While Loop,在下面的代码中,我希望计数器保持在0,而不是在一只股票达到0时进入负数,这将继续向下计数其他项目 cheese = 1 sausage = 3 tomato = 3 while cheese > 0 or sausage > 0 or tomato > 0: print("Cheese stock:") print(cheese) print("Sausage stock:") print(sausage) prin
cheese = 1
sausage = 3
tomato = 3
while cheese > 0 or sausage > 0 or tomato > 0:
print("Cheese stock:")
print(cheese)
print("Sausage stock:")
print(sausage)
print("Tomato stock:")
print(tomato)
cheese -=1
sausage -=1
tomato -=1
我完全理解为什么它会运行到负数,“or”运算符意味着它会这样做,但是如果我使用“and”运算符,它将只运行一次,这是可以理解的。使用条件语句来实现这一点:
cheese = 1
sausage = 3
tomato = 3
while cheese > 0 or sausage > 0 or tomato > 0:
print("Cheese stock:")
print(cheese)
print("Sausage stock:")
print(sausage)
print("Tomato stock:")
print(tomato)
if cheese > 0:
cheese -=1
if sausage > 0:
sausage -=1
if tomato > 0:
tomato -=1
只有当计数器的值为正整数(大于零)时,才应递减计数器。
使用
if
conditional语句,以下应给出结果:
cheese = 1
sausage = 3
tomato = 3
while cheese > 0 or sausage > 0 or tomato > 0:
print("Cheese stock: \n", cheese)
print("Sausage stock: \n", sausage)
print("Tomato stock: \n", tomato)
if cheese > 0: cheese -=1
if sausage > 0: sausage -=1
if tomato > 0: tomato -=1