简体   繁体   中英

Looping back to a specific line in Python

I am writing a program (for no specific purpose), where I take orders from users, which run the program. At some point, I ask them if they are happy with their decision. They have the option to "say" Yes or No. If their answer is no, I need the program to loop back to a specific point in the code. How can I do that?

Here's the code:

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

I am new relatively new to the coding scene. Thank you in advance for any answers.

You can wrap your code inside a while loop:

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

To go to a specific point in the code, you will have to use this pattern (or something similar) several times.

You can use break statement to stop the(infinite)loop while continue is used to skip something that is what you're looking for here.
So, your code needs to be like this

# 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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