首页 > 解决方案 > 为什么当我设置 while var != 0 时循环不会在 0 计数处中断

问题描述

我正在为我的班级编写一个程序,该程序是输入您要在线购买的商品,然后输入价格。我创建了一个 while 循环,一旦用户购买的商品总数为零,该循环就会中断,这样我就可以获取他们想要的所有商品。出于某种原因,尽管当变量 totalItems 达到零时(我知道这是因为我将每一行都打印出来),但循环并没有中断,实际上它一直处于负数状态。

def main():
    totalItems = int(input('How many items are you buying? '))
    while totalItems != 0:
        item1 = input('What is the first item? ')
        cost1 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item2 = input('What is the second item? ')
        cost2 = input('What is the price of the second item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item3 = input('What is the third item? ')
        cost3 = input('What is the price of the third item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item4 = input('What is the fourth item? ')
        cost4 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
        print(totalItems)
        item5 = input('What is the first item? ')
        cost5 = input('What is the price of the first item? ')
        totalItems = totalItems - 1
    print('done')


main()

标签: pythonwhile-loop

解决方案


只有在其中的所有代码都运行之后,才会检查循环条件。而且由于它在那里减少了五次,它很有可能从 2 变为 -3,而且它们都不等于 0,所以它继续。

此外,您在那里有五倍或多或少相同的代码。为什么?只要确保它在那里一次。

警卫应该是while totalItems > 0:,只是一点防御性编程,以确保循环结束,即使错误导致变量低于 0。

最后,不要有变量“cost1”、“cost2”、“cost3”等等,尤其是如果你事先不知道你需要多少。这就是列表的用途。


推荐阅读