[英]Infinite loop error in python code
I am learning how to code through this book called "Headfirst Programming", which I am really enjoying so far. 我正在通过名为《 Headfirst编程》的书来学习如何编码,到目前为止,我真的很喜欢。
One of the projects in the book uses the following code: 本书中的一个项目使用以下代码:
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])
I can see the logic behind using the "if choice == option then running = false" code (it lets the user add an arbitrary number of items), but this code, as is, runs an infinite loop in the shell. 我可以看到使用“ if choice ==选项然后运行= false”代码的逻辑(它允许用户添加任意数量的项目),但是该代码照原样在Shell中运行无限循环。 This is strange because I copied it directly from the book and the author is using python 3.0, as am I.
这很奇怪,因为我直接从书中复制了它,而作者和我一样都在使用python 3.0。
Does anyone have a guess as to why this code runs an infinite loop and how to solve this problem, while keeping the code's core functionality intact? 是否有人猜测为什么该代码会运行无限循环以及如何解决此问题,同时又要保持代码的核心功能完整?
Thanks 谢谢
As you've probably read, Python uses indentation to identify blocks of code. 您可能已经读过,Python使用缩进来标识代码块。
So... 所以...
while running:
option = 1
for choice in items:
print(str(option) + ". " + choice)
option = option + 1
will run forever, and 将永远运行,并且
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])
is never reached. 永远不会到达。 Simply fix the indentation and you should be right.
只需修复缩进,您应该是正确的。
It's pretty clear that the indentation here is wrong -- since the whole body of the function should be indented relative to the def save_transaction(price, credit_card, description):
line. 很明显,这里的缩进是错误的-因为函数的整体应该相对于
def save_transaction(price, credit_card, description):
行缩进。
Hence, I suspect that there's also a problem with the indentation below the while running
line, and that the lines which change the value of running
should be inside the loop. 因此,我怀疑
while running
行下方的缩进也存在问题,并且更改running
值的running
应位于循环内。
You need to indent forward all the lines starting from print(str(option) + ". Quit"))
. 您需要缩进从
print(str(option) + ". Quit"))
开始的所有行。 Align them at the same level as for choice in items:
. 将它们对齐到与
for choice in items:
相同的级别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.