python - 为什么当我设置 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()
解决方案
只有在其中的所有代码都运行之后,才会检查循环条件。而且由于它在那里减少了五次,它很有可能从 2 变为 -3,而且它们都不等于 0,所以它继续。
此外,您在那里有五倍或多或少相同的代码。为什么?只要确保它在那里一次。
警卫应该是while totalItems > 0:
,只是一点防御性编程,以确保循环结束,即使错误导致变量低于 0。
最后,不要有变量“cost1”、“cost2”、“cost3”等等,尤其是如果你事先不知道你需要多少。这就是列表的用途。
推荐阅读
- java - 什么样的设计模式适合这个程序?
- javascript - 如何在 Node JS 应用程序中使用 Zoho API?
- python - 使用 tensorflow 数据集导致 keras 值错误的原因是什么?
- azure - 如何在 Cosmos DB 容器上显示唯一键?
- c# - 尝试从 ZipArchive 中提取 ZipFile 时出现 System.MissingMethodException
- heuristics - 在 Python 中构建 MINLP 启发式模型
- react-redux - Redux/React 状态规范化——为什么要维护一个单独的 ID 数组?
- python - TypeError:需要一个类似字节的对象,而不是套接字编程中的“str”
- reactjs - exoplayer 和 react native 寻求桥接问题
- c - Windows - 在重叠 I/O 正在进行时调用 CloseHandle() 是否安全?