python代码中的无限循环错误

AME*_*AME 0 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])
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Ada*_*ers 8

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

所以...

while running:
      option = 1
      for choice in items:
         print(str(option) + ". " + choice)
         option = option + 1
Run Code Online (Sandbox Code Playgroud)

将永远运行,并且

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])
Run Code Online (Sandbox Code Playgroud)

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

  • 为什么Python的正确缩进比任何其他语言的正确缩进更难? (3认同)
  • 如果一本关于另一种语言的书的编辑弄乱了它的缩进,它看起来很难看.如果python书的编辑器弄乱了缩进,那么代码的含义就会改变.书籍的水平空间非常有限,因此不能分解线条可能会让生活变得更加艰难. (3认同)