Python代码中的无限循环错误

0 投票
3 回答
3763 浏览
提问于 2025-04-15 17:26

我正在通过一本叫《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”这段代码(它让用户可以添加任意数量的项目),但是这段代码在运行时却在命令行中出现了无限循环。这很奇怪,因为我直接从书上复制的代码,作者用的是Python 3.0,而我也是用这个版本。

有没有人能猜到为什么这段代码会出现无限循环,以及如何解决这个问题,同时又不影响代码的核心功能呢?

谢谢!

3 个回答

0

这里的缩进明显是错的——因为整个函数的内容应该相对于 def save_transaction(price, credit_card, description): 这一行进行缩进。

所以,我怀疑在 while running 这一行下面的缩进也有问题,改变 running 值的那些行应该放在这个循环里面。

0

你需要把从 print(str(option) + ". Quit")) 开始的所有行向右缩进。让它们和 for choice in items: 这一行对齐,保持在同一个缩进层级。

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])

这部分代码永远不会被执行。只要调整好缩进就可以解决这个问题。

撰写回答