簡體   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