我对我的代码略有不满。我对python的了解非常有限,但我试图退出循环来显示某人选择的项目。我试过if语句不起作用。考虑一个def语句,但不太确定如何实现它和Return是一个想法,但显然需要def语句才能工作。
非常感谢任何帮助。
P.S我不知道如何上传CSV文件,但以下链接是我的目标: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()
答案 0 :(得分:2)
您需要做的就是检查退出条件,然后使用break
statement来摆脱循环。
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])
这种while True
+ other_code
+ if condition: break
模式很常见,至少有两个好处:
答案 1 :(得分:0)
我喜欢的一个很酷的技巧
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)