Python点餐程序如何实现跳转回指定代码行进行循环重选
电子食堂点餐程序跳转功能实现方案
核心实现思路
Python 没有其他语言里的 goto 跳转语法,对于新手最容易理解的实现方式就是把独立流程封装为函数,需要回到对应步骤时直接调用对应函数即可:
- 把选餐逻辑封装为独立函数,需要回到选餐步骤时直接调用该函数
- 把选饮品逻辑封装为独立函数,需要回到选饮品步骤时直接调用该函数
- 新增订单存储变量,保存用户已经选择的餐品、饮品和累计金额,修改/追加订单时不会丢失之前的选择
前置修复
你原有代码存在两处会导致运行报错的问题,需要先调整:
- 缺少饮品价格字典,最后结算时对字符串求和会报错,需要补充
DrinkPrices字典 - 选餐时的输入校验逻辑重复,可以合并简化
完整可运行修改后代码
import datetime import time # 常量定义 date = time.strftime("%A") MenuItems = {0:["Beef steak (0.5 kg) with french fries or basmati rice and mushroom sauce.","Patata con pollo (potato slices with chicken and cooked cream) with cooked vegetables.","Moussaka with green beans, carrots and broccoli \033[92m(vegeterian)\033[37m."], 1:["Beef stroganoff with noodles.","Risotto with pork meat and cooked vegatables.","Gratinated cottage cheese pancakes \033[92m(vegeterian)\033[37m."], 2:["Spaghetti carbonara.","Noodle soup with cut up parsley.","Gnocchi with tomato sauce and sauteed vegetables \033[92m(vegeterian)\033[37m."], 3:["Fried hake with cooked potatoes.","Pizza Palermo (tomato sauce, cheese, ham, pancetta and mushrooms.","Pizza Margherita (tomato sauce, cheese, olives) \033[92m(vegeterian)\033[37m."], 4:["Warm salad with octopus.","Chicken filet with paears in spicy sauce.","Gratinated cheese tortellini with spinach, sour cream and an egg \033[92m(vegeterian)\033[37m."], 5:["Black angus burger with cheddar.","Macaroni with beef filet and tomatoes.","Spaghetti with vegetable sauce \033[92m(vegeterian)\033[37m."]} DrinkItems = {0:["Soft beverages","Carbonated beverages","Alcoholic beverages","Hot beverages"], 1:["Cedevita (0,5l)","Ice Tea (0,5l)","Water (0,5l) \033[92m(FREE)\033[37m","Apple juice (0,25l)","Orange juice (0,25l)","Strawberry juice (0,25l)","Peach juice (0,25l)","Lemonade (0,5l)","Water with taste (0,5l)"], 2:["Coca Cola (0,25l)","Coca Cola Zero (0,25l)","Coca Cola Zero Lemon (0,25l)","Cockta (0,25l)","Fanta (0,25l)","Schweppes Bitter Lemon (0,25l)","Schweppes Tonic Water (0,25l)","Schweppes Tangerine (0,25l)","Radenska (0,25l)","Sprite (0,25l)","Red Bull (0,25l)"], 3:["Laško beer (0,33l)","Union beer (0,33l)","Malt (0,33l)","Non-alcoholic beer (0,33l)","Corona Extra (0,33l)","Guiness Extra Stout (0,33l)","Sparkling wine (0,10l)","White wine (0,10l)","Red wine (0,10l)","Blueberry Schnapps (0,03l)","Grappa (0,03l)","Stock (0,3l)","Jägermeister (0,03l)","Liquer (0,03l)","Rum (0,03l)","Tequila (0,03l)","Vodka (0,03l)","Gin (0,03l)","Whiskey (0,03l)","Cognac (0,03l)"], 4:["Coffee","Coffee with milk","Cocoa","Hot Chocolate","Irish Coffee","Tea (green, black, herbal, chamomile)"]} MenuPrices= {0:[6.00, 4.50, 4.50], 1:[5.00, 4.50, 4.00], 2:[5.00, 4.00, 4.50], 3:[4.50, 4.50, 4.50], 4:[4.50, 5.00, 4.00], 5:[5.00, 5.00, 4.00]} # 补充的饮品价格字典,可根据实际价格调整 DrinkPrices = { 1:[2.0, 2.0, 0.0, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0], 2:[2.5,2.5,2.5,2.5,2.5,3.0,3.0,3.0,2.5,2.5,4.0], 3:[3.0,3.0,2.5,2.5,4.0,5.0,3.5,3.5,3.5,4.0,4.0,10.0,5.0,5.0,5.0,5.0,5.0,5.0,6.0,6.0], 4:[1.5,2.0,2.0,2.5,5.0,1.5] } todayWeekday = datetime.datetime.today().weekday() # 封装选餐函数 def order_menu(): print ("") time.sleep(1) while True: menu = int(input("Please choose a menu item by typing in a number from 1 to 3: "))-1 if 0 <= menu <3: break print("Sorry, we do not have more than 3 menu items per day. Please choose a menu item from 1 to 3.") print("Great choice! You have selected: "+MenuItems[todayWeekday][menu]) price = MenuPrices[todayWeekday][menu] print("The meal price is: {:,.2f}€".format(price)) # 返回选的餐品名称和价格 return MenuItems[todayWeekday][menu], price # 封装选饮品函数 def order_drink(): print ("------------------------------------------------------------") print ("") time.sleep(2) print("Please choose a type of beverage you would like to order:") time.sleep(1) for idx,item in enumerate(DrinkItems[0]): print(f"{idx+1}. {item}") print("") time.sleep(0.5) while True: category = int(input("Enter your number here: ")) if 1<= category <=4: break print("Invalid category, please choose 1-4.") print("") print("You chose \033[1m" +DrinkItems[0][category-1] +"\033[0m. Here is a list:") for idx,item in enumerate(DrinkItems[category]): print(f"{idx+1}. {item}") print("") time.sleep(0.5) while True: drink = int(input("Please choose a beverage by entering the number in front of your desired beverage: "))-1 if 0<= drink < len(DrinkItems[category]): break print("Invalid number, please try again.") drink_name = DrinkItems[category][drink] drink_price = DrinkPrices[category][drink] print(f"\nYou chose {drink_name}, price: {drink_price:.2f}€") # 返回选的饮品名称和价格 return drink_name, drink_price # 主流程 if __name__ == "__main__": # 欢迎语 print ("Hello! Welcome to the e-Canteen!") print ("") time.sleep(1) print ("Today is \033[1m" + (date) + "\033[0m.") time.sleep(1) # 判断是否营业 if todayWeekday >=6: print ("Sorry, we're closed.") exit() # 展示当日菜单 print ("We are serving:") for idx, x in enumerate(MenuItems[todayWeekday]): print(f"{idx+1}. {x}") time.sleep(0.5) # 存储订单的变量 order_list = [] total_price = 0.0 # 首次选单 menu_name, menu_p = order_menu() order_list.append(menu_name) total_price += menu_p drink_name, drink_p = order_drink() order_list.append(drink_name) total_price += drink_p # 循环处理用户修改/追加需求 while True: decision = input("\nAre you happy with your current order? (yes/no) ").lower() if decision == 'yes': additional = input("Great! Would you like to order anything else? (yes/no) ").lower() if additional == "no": print("Awesome! The program will now summ up your price. Please wait a moment...") time.sleep(2) break what = input("What else would you like to order (menu, drink or both)? ").lower() else: change = input("I'm sorry to hear that. What would you like to change (menu, drink or both)? ").lower() what = change # 如果是修改需求,可以清空之前的餐/饮品,不需要的话删掉下面几行即可 if what in ["menu", "both"]: total_price -= menu_p order_list.remove(menu_name) if what in ["drink", "both"]: total_price -= drink_p order_list.remove(drink_name) # 根据用户选择调用对应函数 if what in ["menu", "both"]: print("Redirecting to menu page...") menu_name, menu_p = order_menu() order_list.append(menu_name) total_price += menu_p if what in ["drink", "both"]: print("Redirecting to drink page...") drink_name, drink_p = order_drink() order_list.append(drink_name) total_price += drink_p # 结算 print("\n===== Your Order =====\n") for item in order_list: print(f"- {item}") print(f"\nTotal amount: {total_price:.2f}€") print("\nThank you for your order!")
自定义调整说明
- 如果需要支持追加订单而非修改原有订单,删掉修改需求处清空旧订单的代码即可
- 饮品价格可以直接修改
DrinkPrices字典里的数值,和DrinkItems里的顺序一一对应即可
内容的提问来源于stack exchange,提问作者Jon Krajic Tomin
相关产品推荐
相关产品推荐

