Reputation: 7
I am slightly stuck on my code. My knowledge of python is very limited but I am trying to quit the loop to display the items someone selects. I have tried if statements that don't work. Considered a def statement but not too sure how to implement it and Return is an idea but obviously needs the def statement to work.
Any help is much appreciated.
P.S I have no idea how to upload the CSV file but, the following link is what I am aiming to do: https://dl.dropboxusercontent.com/u/31895483/teaching%20delivered/FE/2013-14/Access%20-%20Prg/assignment/menu2.swf
import csv
f = open("menu.csv", "r") #Has items for the menu and is read only
spent = 0
order = []
menu = []
for line in f:
line = line.rstrip("\n")
dish = line.split(',')
menu = menu + [dish]
f.close()
#Menu imported into python, no need to leave file open
while True:
dishes = -1
for dish in menu:
if dishes == -1:
print ("Dish No".ljust(10), end="")
else:
print(str(dishes).ljust(10), end="")
print(dish[0].ljust(15), end="")
print(dish[1].ljust(30), end="")
print(dish[2].ljust(15), end="")
print(dish[3], end="\n\n")
dishes += 1
reply = input("Please choose your first item: ")
print()
spent = spent + float(menu[int(reply)+1][2])
order = order + [reply]
print(len(order), "choices made so far =", order, "and cost = £ ", spent)
print()
print ("Please choose an item from the menu (0-9 or press Q to end): ")
print()
Upvotes: 0
Views: 68
Reputation: 17168
All you need to do is check for the exit condition, and then use the break
statement to break out of the loop.
while True:
# other stuff here
reply = input("Please choose a menu item:")
if reply.upper() == 'Q':
break # Break out of the while loop.
# We didn't break, so now we can try to parse the input to an integer.
spent = spent + float(menu[int(reply)+1][2])
This pattern of while True
+ other_code
+ if condition: break
is pretty common, which has at least two benefits:
Upvotes: 2
Reputation: 113988
a cool trick that I like
my_menu_choices = iter(lambda : input("Please choose a menu item:").lower(),"q")
for i,dish in dishes:
print("%d. %s"%(i,dish))
print("Q. type q to QUIT")
my_menu_choices = list(my_menu_choices)
print("You Choose: %s"%my_menu_choices)
Upvotes: 0