繁体   English   中英

循环回到 Python 中的特定行

[英]Looping back to a specific line in Python

我正在编写一个程序(没有特定目的),我在那里接受运行该程序的用户的命令。 在某些时候,我会问他们是否对自己的决定感到满意。 他们可以选择“说”是或否。如果他们的回答是否定的,我需要程序循环回到代码中的特定点。 我怎样才能做到这一点?

这是代码:

import datetime
import calendar
import time
import colorsys
import math


# Definitions
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]}

# Introduction of the Bartender
print ("Hello! Welcome to the e-Canteen!")
print ("")
time.sleep(1)
print ("Today is \033[1m" + (date) + "\033[0m.")
time.sleep(1)

# Menus available for current day
todayWeekday = datetime.datetime.today().weekday()
if todayWeekday < 6:
    print ("We are serving:")
    for x in MenuItems[todayWeekday]:
        print(str(MenuItems[todayWeekday].index(x)+1)+".", x)
        time.sleep(0.5)
# Canteen is closed on Sunday
else:
    print ("Sorry, we're closed.")
    exit()
            
        
# Ordering the menus
print ("")
time.sleep(1)
menu = int(input("Please choose a menu item by typing in a number from 1 to 3: "))-1
print ("")
if menu < int(3):
    print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
    print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Person chooses higher menu item than 3
else:
    print("Sorry, we do not have more than 3 menu items per day. Please choose a menu item from 1 to 3.")
    time.sleep (1)
    while menu >= 3:
         menu = int(input("Please choose a menu by typing in a number from 1 to 3: "))-1
# Person chooses a menu item from 1 to 3
         if menu < 3:
            print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
            print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))

# Any additional orders



# Choosing beverage category
print ("------------------------------------------------------------")
print ("")
time.sleep(2)
category = DrinkItems[0]
print("Please choose a type of beverage you would like to order:")
time.sleep(1)
for x in DrinkItems[0]:
    print(str(DrinkItems[0].index(x)+1)+".", x)
print("")
time.sleep(0.5)
# Choosing beverage
category = int(input("Enter your number here: "))
print("")
print("You chose \033[1m" +DrinkItems[0][category-1] +"\033[0m. Here is a list:")

for x in DrinkItems[category]:
    print(str(DrinkItems[category].index(x)+1)+".", x)
print("")
time.sleep(0.5)
drink = int(input("Please choose a beverage by entering the number in front of your desired beverage: "))-1
    
    
# User deciding if she/he is happy with her/his decision
decision = input("\nYou chose " +DrinkItems[category][drink] +". Are you happy with your decision? ").lower()
if decision == 'yes':
    additional = input("Great! Would you like to order anything else? ").lower()
    if additional == "yes":
        what = input("What else would you like to order (menu, drink or both)? ").lower()
        if what == "menu":
            print("I understand. The program will return you to the menus.")
        elif what == "drink":
            print("I understand. The program will return you to the drinks.")
        elif what == "both":
            print("I understand. The program will return you back to the menus (no orders until now will be lost).")
    elif additional == "no":
        print("Awesome! The program will now summ up your price. Please wait a moment...")
        time.sleep(2)
elif decision == "no":
    change = input("I'm sorry to hear that. What else would you like to change (menu, drink or both)? ").lower()
    if change == "menu":
        print("I understand. The program will return you to the menus.")
    elif change == "drink":
            print("I understand. The program will return you to the drinks.")
    elif change == "both":
        print("I understand. The program will return you back to the menus.")




# Any additional beverages



# Billing
print(sum(DrinkItems[category][drink]))


# End

我是编码领域的新手。 预先感谢您提供任何答案。

您可以将代码包装在 while 循环中:

while True: 
    // your code
    // at some point in the code:
    happiness = input("Are you happy?")
    if happiness == "yes":
        break

要转到代码中的特定点,您必须多次使用此模式(或类似模式)。

您可以使用break语句来停止(无限)循环,而continue用于跳过您在此处寻找的内容。
所以,你的代码需要是这样的

# User deciding if she/he is happy with her/his decision
while True:
    decision = input("\nYou chose "+". Are you happy with your decision? ").lower()
    if decision == 'yes':
        additional = input("Great! Would you like to order anything else? ").lower()
        if additional == "yes":
            what = input("What else would you like to order (menu, drink or both)? ").lower()
            if what == "menu":
                print("I understand. The program will return you to the menus.")
            elif what == "drink":
                print("I understand. The program will return you to the drinks.")
            elif what == "both":
                print("I understand. The program will return you back to the menus (no orders until now will be lost).")
                break 
        elif additional == "no":
            print("Awesome! The program will now summ up your price. Please wait a moment...")
            time.sleep(2)
            break 
    elif decision == "no":
        continue 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM