python代码中的无限循环错误

时间:2009-12-29 10:01:44

标签: python loops

我正在学习如何通过这本名为“Headfirst Programming”的书进行编码,到目前为止我真的非常喜欢这本书。

本书中的一个项目使用以下代码:

def save_transaction(price, credit_card, description):
file = open("transactions.txt", "a")
file.write("%s%07d%s\n" % (credit_card, price * 100, description))
file.close()


items = ['Donut','Latte','Filter','Muffin']
prices = [1.50,2.0,1.80,1.20]` 
running = true

while running:
      option = 1
      for choice in items:
         print(str(option) + ". " + choice)
         option = option + 1
print(str(option) + ". Quit"))
choice = int(input("choose an option: "))
if choice == option:
   running = false
else: 
   credit_card = input("Credit card number: ")
   save_transaction(prices[choice - 1], credit_card, items[choice - 1])

我可以看到使用“if choice == option then running = false”代码背后的逻辑(它允许用户添加任意​​数量的项),但是这个代码在shell中运行一个无限循环。这很奇怪,因为我直接从书中复制了它,作者正在使用python 3.0,就像我一样。

有没有人猜测为什么这段代码运行无限循环以及如何解决这个问题,同时保持代码的核心功能完好无损?

由于

3 个答案:

答案 0 :(得分:8)

正如您可能已经阅读过的,Python使用缩进来识别代码块。

因此...

while running:
      option = 1
      for choice in items:
         print(str(option) + ". " + choice)
         option = option + 1

将永远运行,

print(str(option) + ". Quit"))
choice = int(input("choose an option: "))
if choice == option:
   running = false
else: 
   credit_card = input("Credit card number: ")
   save_transaction(prices[choice - 1], credit_card, items[choice - 1])

永远不会到达。只需修复缩进,你应该是对的。

答案 1 :(得分:0)

很明显,这里的缩进是错误的 - 因为函数的整个主体应该相对于def save_transaction(price, credit_card, description):行缩进。

因此,我怀疑while running行下方的缩进也存在问题,并且更改running值的行应位于循环内。

答案 2 :(得分:0)

您需要从print(str(option) + ". Quit"))开始缩进所有行。将它们与for choice in items:处于同一级别对齐。