I am learning how to code through this book called “Headfirst Programming”, which I am really enjoying so far.
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. This is strange because I copied it directly from the book and the author is using python 3.0, as am I.
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.
So…
will run forever, and
is never reached. Simply fix the indentation and you should be right.