我正在学习如何通过这本名为"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,就像我一样.
有没有人猜测为什么这个代码运行无限循环以及如何解决这个问题,同时保持代码的核心功能完好无损?
谢谢
您可能已经阅读过,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)
永远不会到达.只需修复缩进,你应该是对的.