I cant pick a choice after looping - python

def print_menu():
print('1. American')
print('2. Asian')
print('3. Indian')
print('4. Mexican')
print('5. French')
print('6. Italian')
print('7. Seafood')
print('8. Pizza')
print_menu()
menu = input('\nChoose where you want to eat from-->')
if menu == "1":
def american_menu():
print('1. Dempsey Burger Pub')
print('2. Redrock Canyon Grill-Wichita')
print("3. Cheddar's Scratch Kitchen")
print("4. Neighbors| Restaurant & Bar")
print("5. The Kitchen")
print("6. Firebirds Wood Fired Grill")
print("7. Chicken and Pickle")
american_menu()
american = input("\nChoose which American Restaurant--> ")
if american == "1":
print("\nCall Dempsey Burger Pub")
while True:
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")
break
so i tried looping it so it goes back to choose again from the Cuisines and moving on to where you want to eat but so far, it just asks the go_back, after i say yes...it keeps repeating the go_back again
any help will be appreciated. Thanks. i want it to loop back to the choices, pick the choice and sub-choice i selected rather than it just picking the choice and not do anything. Thanks again
NB:this is an assignment and i am stuck plus i had a list of the choices but couldnt post it due to the site.

Write a while loop for print_menu and change continue with break
def print_menu():
while True:
#Use 2 while loops if you want. But the loop you are using is not needed
while True:
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
break
else:
print("We'll continue with your current choice")
break
Second Option:
def print_menu():
while True:
#Just use "while" here instead of the second one
go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")

You don't need to use a while True loop at all. It might cause problems with infinite looping. You can avoid it by calling a new function check_if_wants_to_order_again after a user has chosen his menu in print_menu().
def print_menu():
print('1. American')
print('2. Asian')
print('3. Indian')
print('4. Mexican')
print('5. French')
print('6. Italian')
print('7. Seafood')
print('8. Pizza')
menu = input('\nChoose where you want to eat from-->')
if menu == "1":
american_menu()
check_if_wants_to_order_again()
def american_menu():
print('1. Dempsey Burger Pub')
print('2. Redrock Canyon Grill-Wichita')
print("3. Cheddar's Scratch Kitchen")
print("4. Neighbors| Restaurant & Bar")
print("5. The Kitchen")
print("6. Firebirds Wood Fired Grill")
print("7. Chicken and Pickle")
american = input("\nChoose which American Restaurant--> ")
if american == "1":
print("\nCall Dempsey Burger Pub")
def check_if_wants_to_order_again():
go_back = input("Will you like to try another menu option? Enter \"Yes\" or \"No\":")
if go_back == "Yes":
print_menu()
else:
print("We'll continue with your current choice")
print_menu()

When you continue your loop, you're calling print_menu() again, but you aren't doing any of the other things that need to follow print_menu() in order to prompt the user to make another choice.
Give this a shot:
# Define the menus as dictionaries.
# The key is the number that the user will pick,
# the value is the selected item.
# Main menu -- pick a cuisine.
main_menu = {
"1": "American",
"2": "Asian",
"3": "Indian",
"4": "Mexican",
"5": "French",
"6": "Italian",
"7": "Seafood",
"8": "Pizza",
}
# American restaurant menu.
american_menu = {
"1": "Dempsey Burger Pub",
"2": "Redrock Canyon Grill-Wichita",
"3": "Cheddar's Scratch Kitchen",
"4": "Neighbors| Restaurant & Bar",
"5": "The Kitchen",
"6": "Firebirds Wood Fired Grill",
"7": "Chicken and Pickle",
}
# This dict maps each cuisine name to the appropriate submenu.
cuisine_menus = {
"American": american_menu,
# "Asian": asian_menu,
# "French": french_menu,
# ...
}
# This dict maps each restaurant name to its contact info.
contact_info = {
"Dempsey Burger Pub": (
"(316) 425-3831",
"https://www.dempseysburgerpub.com/"
),
"Redrock Canyon Grill-Wichita": (
"(316) 636-1844",
"https://www.redrockcanyongrill.com/"
),
# ...
}
def print_menu(menu):
"""Print a menu, e.g. '1. American'..."""
for k, v in menu.items():
print(f"{k}. {v}")
def contact_restaurant(restaurant):
"""Contact a restaurant. Raises KeyError if we don't have contact info."""
phone, website = contact_info[restaurant]
print(restaurant)
print(f"Phone: {phone}")
print(f"Website: {website}")
# maybe do something with website to open a browser? idk
# Interactive loop. Go through the menus in turn,
# and repeat when done or when they enter something invalid.
# Break the loop once they finish picking a restaurant.
while True:
# Main menu (pick a cuisine)
print_menu(main_menu)
pick = input('\nChoose where you want to eat from-->')
# Error checking for invalid picks.
if pick not in main_menu:
print("Please select one of the listed options.")
continue
cuisine = main_menu[pick]
if cuisine not in cuisine_menus:
# This happens if they picked something that was in main_menu
# but not in cuisine_menus yet because we haven't written that part.
print("Oops! Haven't implemented that one yet.")
print(f"Try {', '.join(cuisine_menus)}")
continue
# Now we have a valid main menu pick that we can continue with.
cuisine_menu = cuisine_menus[cuisine]
# Print the menu and ask them to pick an item from that.
print_menu(cuisine_menu)
pick = input(f"\nChoose which {cuisine} Restaurant--> ")
if pick not in cuisine_menu:
print("Sorry, not an option. Let's start over.")
continue
restaurant = cuisine_menu[pick]
if restaurant not in contact_info:
print(f"Oops, we don't have contact info for {restaurant}.")
print("Let's start over...")
continue
print(f"\nCall {restaurant}")
# Prompt them to start over. If they don't, break the loop.
pick = input("Will you like to try another menu option?: ")
if pick != "Yes":
print("We'll continue with your current choice")
break
# Now the user has picked a restaurant to contact,
# so go ahead and contact them.
contact_restaurant(restaurant)
Note that all of the interaction happens inside the while True loop. Any time there's a continue within that loop, it goes back to the print_menu(main_menu) at the start, and then continues from there.

Related

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

Part of my Python Code is not functioning, but all other parts are

I have a code in Python that I recently created for a Maths Assignment, but part of it is not working.
So it asks the user to select a choice, but when I tested it, all other options (which I took out) worked for me, but when I entered "4", it wouldn't work. Instead, it just reprinted everything and asked for my choice again.
FYI: I have taken out the other options, because they aren't needed here.
Does anybody have a solution though? Because whatever I do, it doesn't seem to function or work.
Here's the part of my code that has the problem:
#This part greets the user, and lets the user know that the application has started
print("Hello there!")
#This starts off the loop, but this variable may be changed later on
cont = "yes"
#This is the actual loop
while cont == "yes" or cont == "Yes" or cont == "YES":
print("Choose an option below:")
#This shows the options
print("1) Calculate the value of different product sizes")
print("2) Calculate the sale price")
print("3) Calculate the discount")
print("4) Create a shopping list")
print("5) Create a receipt that shows costs")
print("6) Exit")
#This part lets the user choose what they would like to do
option = float(input("Choose an option (1/2/3/4/5/6): "))
#This is what happens if the user chooses Option 4
#This is the "Shopping list" part of the application below
if option == 4:
sl = []
import os,sys,time
try:
f = open("Shopping_List.txt","r")
for line in f:
sl.append(line.strip())
f.close
except:
pass
def mainScreen():
os.system("cls")
print("Just a couple reminders:")
print("Your shopping list contains", len(sl), "items so far.")
print("If items aren't deleted from the list after use, they'll remain there.")
print("Choose an option below:")
print("1) Add an item to the list")
print("2) Delete an item from the list")
print("3) View the list")
print("4) Exit")
asdf = input("Enter your choice here: ")
if len(asdf) > 0:
if choice.lower()[0] == "1":
addScreen
elif choice.lower()[0] == "2":
deleteScreen()
elif choice.lower()[0] == "3":
viewScreen()
elif choice.lower()[0] == "4":
sys.exit()
else:
mainScreen()
else: mainScreen()
def addScreen():
global sl
os.system('cls')
print("Press ENTER if you would like to exit.")
print("Enter the name of the item you would like to add below.")
item = input("Name of item: ")
if len(item) > 0:
sl.append(item)
print("Item has been added.")
saveList()
time.sleep(1)
addScreen()
else:
mainScreen
def viewScreen():
os.system('cls')
for item in sl:
print(item)
print("Press ENTER to exit.")
input()
mainScreen()
def deleteScreen():
global sl
os.system('cls')
count = 0
for item in sl:
print(count, ") - ", item)
count = count + 1
print("Enter the number corresponding to the item you would like to delete.")
chce = ("Number: ")
if len(chce) > 0:
try:
del sl[int(chce)]
print("Item has been deleted.")
saveList()
time.sleep(1)
except:
print("Invalid number.")
time.sleep(1)
deleteScreen()
else:
mainScreen()
def saveList():
f = open("Shopping_List.txt", "w")
for item in sl:
f.write(item + "\n")
f.close()
mainScreen
Thanks in advance.
Here's the solution:
The line at the bottom of my code should be changed from mainScreen to mainScreen(), otherwise it wouldn't do anything. And also, if choice.lower()[0] == "1": addScreen should be if choice.lower()[0] == "1": addScreen(), or otherwise, that part of my code wouldn't function either, which would create further problems.
Credit goes to Keith John Hutchison and MaxiMouse for helping me figure out how to solve my problem, why it didn't work, and for also suggesting improvements to my code.

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

Python Game not going where I want it to go

I have finished my text game in python. But, the only problem I have is that when I type in where to go it doesn't go to that place. It goes to the place under the start not what the user inputted in... I don't see any problems with my if and elif statements but don't know where the problem is... In fact i re-did all the elif and if statements but still have the same problem...
# This displays the map for the user to follow to play the game in another window.
from tkinter import*
window = Tk()
# Name of the window that the map is displayed in.
window.title('The Map')
# Size of the window
canvas = Canvas(window, width = 500, height = 500)
canvas.pack()
# This is the file path of the map.
my_image=PhotoImage(file='C:\\Users\\Oscar\\Desktop\\Bangor Uni S2\\ICP-1025-0 Intro to Intelligent Systems 201718\\Lab4\\map.png')
# Opens the window with the map.
canvas.create_image(0,0, anchor = NW, image=my_image)
# Welcome sign to the game.
def displayIntro():
print (" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(" ~ ~")
print(" ~ ~")
print(" ~ WELCOME TO MILK ~")
print(" ~ ~")
print(" ~ MADE BY: ~")
print(" ~ OSCAR TSANG ~")
print(" ~ ~")
print (" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("")
print("")
intropic()
print("")
def intro():
print()
print(" This is the game MILK!!! ")
print("")
print(" You are Farmer Bob and your objective is to find the lost milk ")
print("")
print(" The lost milk is located somewhere on the map ")
print("")
print("Yo would need to use the map to navigate around the farm to find the precious milk ")
print("")
print(" Only you can find the precious milk ")
print("")
print(" You will be in a farm that you will have to navigate through to get to the milk ")
print("")
print(" You will have no help ")
print("")
print(" There are 9 possibility where the milk can be, but only the map has the answer ")
print("")
print(" Now goodluck in finding the milk... ")
print("")
print("")
print("")
print("")
print("")
print("")
#These are all the nodes to the game milk.
# The starting point of the game.
def start():
print(" You are at the start of the game MILK ")
print("Now you will have to use the map to navigate around the farm to find the almighty, godly, delicious MILK!!!!")
way_picked = input("Do you want to go to the Shop 1, Field , Shop , House , Farm , Dead end, Shop 1, Field 1 ???? > ")
# This is where the user picks where they want to go within the game.
if way_picked.lower() == "Shop 1":
shop1()
elif way_picked.lower() == "Field":
field()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower() == "House":
house()
elif way_picked.lower() == "Farm":
farm()
elif way_picked.lower() == "Dead End":
deadend()
elif way_picked.lower == "Field 1":
field1()
else:
print("")
print("")
print("")
print("")
print("")
# The field node in the game.
def field():
cow()
print( "This isn't where the milk is... ")
print("This is an empty field full of grass with sheeps and cows munching on it 24/7")
print("")
print("")
way_picked = input(" Start, Shop 1 or Shop ??? > ")
# This is where the user picks where they want to go when they they reach field node.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower == "Shop 1":
shop1()
else:
print("")
print("")
print("")
print("")
print("")
# The shop node in the game where Bob gets his eqipment from.
def shop():
print(" This isn't where the milk is... ")
print(" This is the farmers equipment shop.'.. ")
way_picked = input(" Start, Field or House ??? > ")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "House":
House()
elif way_picked.lower == "Field ":
field()
else:
print("")
print("")
print("")
print("")
print("")
# House node of the game where Bob lives.
def house():
print(" This is your house.... ")
print(" This isn't where the milk is... ")
print(" Look harder Bob!!!! ")
way_picked = input(" Start , Shop , Farm ??? > ")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop":
shop()
elif way_picked.lower == "Farm":
farm()
else:
print("")
print("")
print("")
print("")
print("")
# The farm node of the game
def farm():
print(" This is the farm.... ")
print(" The milk is nowhere to be seen ")
print(" This is where all the equipment is held... ")
way_picked = input(" Start , Dead End or House??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Dead End":
deadend()
elif way_picked.lower == "House":
house()
else:
print("")
print("")
print("")
print("")
print("")
# This is the dead end of the game where the player has to go back to the previous spot.
def deadend():
print(" This is DEAD END!!!!! ")
print(" You need to go back where you was.... ")
way_picked = input(" Start or Farm ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Farm":
farm()
else:
print("")
print("")
print("")
print("")
print("")
# This is another field kind of like a duplicate to the first field.
def field1():
print(" This is another field!!!!! ")
print(" Not where the milk is!!!!!!!! ")
way_picked = input(" Start , Shop 1 or Road ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Shop 1":
shop1()
elif way_picked.lower == "Road":
road()
else:
print("")
print("")
print("")
print("")
print("")
def shop1():
print(" This is Dominos Pizza ")
print(" This is not where the milk is Bob!!!!!! ")
print("Where do you want to go next:")
way_picked = input(" Start , Field 1 or Field ??? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Start":
start()
elif way_picked.lower() == "Field":
field()
elif way_picked.lower == "Field 1":
field1()
else:
print("")
print("")
print("")
print("")
print("")
# The main road by Bob's farm.
def road():
print(" This is the main road and certainly not whrer the milk is kept ")
print(" Try again Bob ")
print("You are very near the milk...")
print("Do you go forward or backwards????")
way_picked = input("Forwards or Backwards?? >")
# This is where the user picks where they want to go when they they reach shop1.
if way_picked.lower() == "Forwards":
start()
elif way_picked.lower() == "Backwards":
road()
else:
print("")
print("")
print("")
print("")
print("")
# This is where the milk is. When the player reaches this node they win the game.
def milk():
milk1()
print(" Finally!!! Bob you have found the missing milk!!!!! ")
print(" WELL DONE BOB!!!!!!!! ")
print(" NOW DRINK THE MILK BOB!!!!!! ")
mario()
# Prints out all the 10 nodes in my game. And is only using testing to see if every single node prints out as wanted.
displayIntro()
intro()
start()
You are converting the inputted text .lower() and you compare against text that has uppercase in it - this wont work. Fix like this:
if way_picked.lower() == "shop 1":
shop1()
elif way_picked.lower() == "field":
field()
elif way_picked.lower() == "shop":
shop()
elif way_picked.lower() == "house":
house()
elif way_picked.lower() == "farm":
farm()
elif way_picked.lower() == "dead end":
deadend()
elif way_picked.lower() == "field 1":
field1()
where ever you compare. You might also want to use a .strip() to ensure leading/trainling whitespaces are removed as well before comparing them.
Also: please read: How to debug small programs (#1) to get tips how to debug your own programms in a way to find your own errors faster then posting on SO.
One solution would be to make a small function that compares for you:
def comp(textIn, myOption):
"""Returns True if textIn.strip().lower() equals myOption.strip().lower()"""
return textIn.strip().lower() == myOption.strip().lower()
# The starting point of the game.
def start():
print(" You are at the start of the game MILK ")
print("Now you will have to use the map to navigate around the farm to find the almighty, godly, delicious MILK!!!!")
way_picked = input("Do you want to go to the Shop 1, Field , Shop , House , Farm , Dead end, Shop 1, Field 1 ???? > ")
# This is where the user picks where they want to go within the game.
if comp(way_picked,"Shop 1"):
shop1()
elif comp(way_picked,"Field"):
field()
elif comp(way_picked, "Shop"):
shop()
# etcerea ....
The function comp(userInput,"option") will take care of stripping & lowering and comparing and simply return True/False
Edit: other way to deal with this: create dictionary that holds a key (the user input) and the function to call (as value):
def func1():
print("F1")
def func2():
print("F2")
def func3():
print("F3")
def func4():
print("F4")
# function are first class citizens in python, you can store them as
# value (without parentheses) to be called later
options = { "f1" : func1, "f2" : func2, "f3" : func3, "f4" : func4}
while True:
userInput = input("F1 to F4:\n\t").strip().lower() # make input trimmed and lower
if userInput in options:
options[userInput] () # execute the stored function (use value + () to execute)
else:
print("\nWrong input!\n")

How can I return to the top of the script in python?

I have a script in python that consists of multiple list of functions, and at every end of a list I want to put a back function that will let me return to the beginning of the script and choose another list. for example:
list = ("1. List of all users",
"2. List of all groups",
"3. Reset password",
"4. Create new user",
"5. Create new group",
"6. List all kernel drivers",
"7. List all mounts",
"8. Mount a folder",
"9. Exit")
for i in list:
print(i)
And if I choose 1 another list opens:
list = "1) Show user Groups \n2) Show user ID \n3) Show user aliases \n4) Add new aliases \n5) Change password \n6) Back"
print
print list
A more specific example.
You can use a while loop until user explicitly doesnt exits you program.
import os
def show_users():
print("1) show group user")
print("2) go back")
i = int(input())
if i==1:
pass # do something
elif i==2:
show_list()
def show_list():
print("1) list of all users")
print("2) exit")
i = int(input())
if i ==1:
show_users()
elif i==2:
exit(0)
while True:
show_list()
You could do this in a while loop, it just keeps running through these options until you answer 4 to the first question. You can place one while loop somewhere in the other to make it all much more complicated.
keepGoing = True
while keepGoing:
choice1 = raw_input('first answer')
if choice1 == '1':
choice2 = raw_input('second answer')
if choice2 == '1':
print('1 again')
else:
print('something different')
if choice1 == '2':
print('two')
if choice1 == 3:
print('three')
if choice1 == 4:
keepGoing = False

Categories