Looping back to a specific line in Python - 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

Related

I cant pick a choice after looping

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.

How do you make sure that a while loop doesn't loop to a previous input?

My program is simple, even though it is long. It is just a shopping program that displays the user's budget after buying a food object. I am relatively new to Python so my code is pretty messy and needs a lot of work.
My problem is that my program keeps looping back to a previous input instead of the input just put in. An example is I go to a food section and buy a food object, then I leave the section in which the food product is. But when I try to leave my program by typing "Nothing," it goes back to the section which I last inputted. Here are some images for context.
Starting the program by inputting a budget
Going to a food section
Leaving the food section
The wrong loop (the main problem)
Here is the program. Its really messy so I am sorry if it is hard to read.
x = 50 #budget
y = 5 #small budget
#Item Prices
#desserts
candy_bar = 1
candy_bag = 2
ice_cream = 2
#Welcome to the store
print("Hello there, young laddie, young man, young boy! Welcome to the Normal Big Meal Grocery Store, where our store is your store! ;)")
#How much money do you want to spend today
budget = int(input("What is your budget today?")) # at the moment, i do not have a shopping cart
if budget <= y:
print("You literally can only buy like 5 candy bars. You don't have enough money! Go to the clearance store across the street!")
print("**You leave and go to the clearance store...")
exit() #you leave
elif budget <= x:
print("I guess you can buy something...But it's not enough for a big meal! You might need to go to the Normal Medium Meal Grocery Store!")
print("**You leave and go to the Normal Medium Meal Grocery Store...")
exit() #you leave
elif budget >= x:
print("Cool! We have lot of stuff for you to make into a big meal, perhaps even a giant one!!!")
print("**Takes you by the hand and leads you into the beautiful Normal Big Meal Grocery Store...")
#User input for food:
items = input("Do you want dairy, meat, vegetables, fruits, or desserts! Type ‘Nothing’ if you don’t want to buy anything...")
while True:
def all_items():
items = input("Do you want dairy, meat, vegetables, fruits, or desserts! Type ‘Nothing’ if you don’t want to buy anything...")
if items == ("Nothing"):
bye = input("Are you sure you don't want to buy anything? Yes or No?")
if bye == ("Yes"):
print("Thank you for shopping at the Normal Big Meal Grocery Store!!!")
exit()
if bye == ("No"):
all_items()
elif items == ("desserts"):
print("Here are our desserts!\n1. Candy Bar: $1.00\n2. $Candy Bag: $2.00\n3. $Ice Cream: 2.00")
dessert_items = input("What desserts do you want to buy? Type 'Nothing' if you don't want any...")
if dessert_items == ("Candy Bar"):
print("Are you sure you want to buy this?")
candybarQ = input("Yes or no?")
if candybarQ == ("Yes"):
print("You have $",(budget - candy_bar), "left!")
if candybarQ == ("No"):
all_items()
if dessert_items == ("Candy Bag"):
print("Are you sure you want to buy this?")
candybagQ = input("Yes or no?")
if candybagQ == ("Yes"):
print("You have $",(budget - candy_bag), "left!")
if candybagQ == ("No"):
all_items()
if dessert_items == ("Ice Cream"):
print("Are you sure you want to buy this?")
icecreamQ = input("Yes or no?")
if icecreamQ == ("Yes"):
print("You have $",(budget - ice_cream), "left!")
if icecreamQ == ("No"):
all_items()
if dessert_items == ("Nothing"):
print("Are you sure you don't want any?")
nothingQ = input("Yes or no?")
if nothingQ == ("Yes"):
all_items()
if nothingQ == ("No"):
continue
else:
print("Umm. We don't have that...")
all_items()
items = input("Do you want dairy, meat, vegetables, fruits, or desserts! Type
‘Nothing’ if you don’t want to buy anything...")
while True:
Move the items = input() line below the while true: loop so that it asks it every time the loop iterates. Currently you're only asking once and then using that answer as the variable each time the loop starts which is why in this case it will always go back to desert.

How do you call on an attribute of a class, as if its a variable (in python)?

Im new to coding, and pretty confused by the concept of class 's and how to use them. Im making a zork game as a practice exercise and have the following as part of my code:
def buildCharacter():
return(Hero(input("What is your name, traveler? \n> ")))
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
Later in the code, if the player gets 'hurt' I want to be able to reduce health, until its 0 and they 'die'.
I tried doing:
self.health -= 5
if self.health <=0:
exit(0)
but that doesn't work, saying 'self' not defined. How do I call on self.health to change it?
Edit: Ive been told that the whole code should be posted, so here it is:
from sys import exit
import time #Lets you pause the command window for a sec
have_sword = False
gate_unlocked = False
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
def take_dammage(self, dammage):
self.health -= dammage
def getHealth(self):
return self.health
#first room: sphynx with riddle, door with password
def sphynx():
print("You enter a room with a sphynx and a door.")
while True: #create infinite loop to begin again if password unknown
print("What do you do?")
choice = input("\n1) Fight the sphynx \n2) Speak to the sphynx \n3) try the door \n>")
if "attack" in choice or "fight" in choice or "1" in choice:
MyName.health -= 5
print(f"You can't beat a sphynx unarmed! \nHealth is now {MyName.health}")
if MyName.health <= 0:
dead()
elif "speak" in choice or "talk" in choice or "ask" in choice or "question" in choice or "2" in choice:
print("""The sphynx is board, instead of telling you the password easily, it asks you a riddle:
'First think of the person who lives in disguise,
who deals in secrets and tells only lies.
Next, tell me what's always the last thing to mend,
the middle of middle and the end of end?
Fianally, give me a sound often heard
durring the search for a hard to find word.
Now string them together, and answer me this,
what creature would you be unwilling to kiss?'
OK, but how is that going to help you??
"""); time.sleep(1)
elif "door" in choice or "open" in choice or "try" in choice or "3" in choice:
print("What's the password?")
password = input("> ")
if password == "spider":
print("Correct! You go through the open door")
room2()
else: #starts while loop ovewr again
print("Nope. \nTry again. \nMaybe the sphynx knows...")
continue
else: #starts while loop ovewr again
print("naw mate, try again")
def room2():
print("You enter a room with a red door and a blue door.")
global have_sword
while True: #create infinite loop to begin again if door not chosen
choice = input("Which do you enter?\n>")
if "red" in choice:
print("You enter a pitch black room. What do you do?")
darkChoice = input("\n1) Feel for a light swith \n2) Turn around and leave \n3) \"the dark doesn's scare me, I venture forward into the gloom\" \n> ")
while True: #create infinite loop to begin again if no option chosen
if "feel" in darkChoice or "light" in darkChoice or "1" in darkChoice:
print("You find a light switch and turn it on. \nIn the room, you see a small box and a large one.")
while True: #create infinite loop to begin again if no option chosen
print("Which box do you open?")
boxChoice = input("> ")
if "small" in boxChoice or "little" in boxChoice:
print("you open the small box to find a wormhole. \nIt sucks you in and you find yourself BACK in the second room.")
room2()
elif "big" in boxChoice or "large" in boxChoice:
print("You find a sword. \nStow it for later use. \nFor now, go back to the second room")
have_sword = True
room2()
else: #starts while loop over again
print("You gotta pick one.")
else:
dead("you get lost in the darkness and starve.")
elif "b" in choice:
oldShack()
else: #starts while loop ovewr again
print("naw mate, try again")
def oldShack():
print("You enter and old, rickety shack. \nThe paint is peeling, the floorboards sticking up, and ceiling caving in. \nThere's a rusty gate at the back.")
global gate_unlocked
while True: #create infinite loop to begin again if no option chosen
print("What do you do in the shack? ")
choice = input("1) Search under the floorboards \n2) Try the gate \n3) Go back \n> ")
if "check" in choice or "floor" in choice or "board" in choice or "1" in choice:
print("You find a key under the floorboards!")
gate_unlocked = True
elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked == True:
print("You use the key you found, it works!")
cave()
elif "Push really hard" in choice:
print("Damn, you're really strong!")
cave()
elif "door" in choice or "gate" in choice or "2" in choice and gate_unlocked != True:
print("the gate is locked.")
elif "3" in choice or "back" in choice:
room2()
else:
print("naw mate, try again")
def cave():
print("You find yourself in a cave that is home to a collosal, sleeping red dragon. ")
global have_sword
while True:
choice = input("How do you deal with the dragon? \n1) Attack with your sword \n2) Attack unarmed \n3) Speak to the dragon \n4) Run before the dragon wakes \n>")
if "1" in choice and have_sword == True:
print("A mighty battle ensures. \n Using your sword, you slay the dragon \nBefore you stands a great pile of generations of dragon treasure; gold and juels and riches beyond your wildest dreams. \nAt the end of the cave lies a small brown chest. \nDo you: \n1) Take the treasure \n2) Open the box")
rich = input("> ")
while True:
if "1" in rich or "gold" in rich:
dead("A deep voice echos from the depths of the cave: \n'Greed is the downfall of man.' \nThe cave rumbles and collaples around you.")
elif "2" in rich or "box" in rich or "brown" in rich:
print("You open the box to find the deep crimson Dream Stone. \nYou have succesded in your quest, 1) this could save King Arthurs kingdom from *vague, unspecified threat* \nOr... \n2) Or you could sell if and buy a kingdom of you very own!")
success = input("> ")
if "1" in success:
win("You successfully passed all the chalanges!\n")
else:
dead("You walk out of the cave, daydreaming about what life will be like as a king \nWhile you are distracted by your thoughts, you trip over the dead dragons tail and hit your head")
else:
print("Naw mate, try again")
elif ("1" in choice or "sword" in choice) and have_sword != True:
dead("What sword? The dragon eats your face.")
elif "2" in choice and have_sword == True:
dead("Use the damn sword next time...")
elif "2" in choice:
dead("Mate, you think you can take a dragon unarmed and alone?")
elif "3" in choice:
dead("Shoulda invested in some lessons in dragon language;")
elif "4" in choice:
oldShack()
else:
print("naw mate, try again")
def dead(why):
print(why, "you died. well done...")
print(open("DEAD.txt").read()); time.sleep(2) #prints the text of DEAD.txt as an outro to the game
exit(0)
def win(how):
print(how, "You return triumphant to Kind Arthur. \nThe Kingdom shall live in peace another day.")
print(open("WIN.txt").read()); time.sleep(2) #prints the text of WIN.txt as an outro to the game
exit(0)
#intro story, do you accept quest? yes -> sphynx room, no-> are u sure?
def start():
print(open("README.txt").read()); time.sleep(2) #prints the text of README.txt as an into to the game
character = buildCharacter() #goes to the buildCharacter funtion, and assigns the results the name character
print(f"You are {character.name}, a night of King Arther's round table. \nYou have been tasked with finding the Dream Stone \nThe search has clamined many lives. \nYou have 10 health points.")
time.sleep(1/2)
choice = input("\nDo you accept?\n> ")
if "y" in choice:
sphynx()
elif "n" in choice:
print("are you sure?")
sure = input("> ")
if "y" in sure:
print("well that was boring.")
print(open("DEAD.txt").read()); time.sleep(2)
elif "n" in sure:
print("good")
sphynx()
else:
print("Mate, its a yes or no question; are you sure")
elif "Cheet code" in choice:
win("You don't deserve this, but fair is fair. \n")
else:
start("Only you can decide. Now decide.")
def buildCharacter(): #goes to the class Hero (line 8), and creates the hero.name given by the user
MyName = input("What is your name, traveler? \n> ")
return(Hero(MyName, 10)) #takes input and uses that as the object for class Hero
print(Hero())
start()
Define a method in your class named hurt and a getter for health, like this :
class Hero(object): #creates class Hero, Hero has-a name and has-a health
def __init__(self, name, health=10):
self.name = name
self.health = health
def hurt(self,damage):
self.health-= damage
def get_health(self):
return self.health
Then later in the code you can call these methods like this :
hero = Hero("mohsen")
hero.hurt(5)
if hero.get_health()<=0:
exit(0)
I believe this example gets at the question you asked.
class Hero:
def __init__(self):
self.health = 100
Jon = Hero()
Jon.health -= 20
print(Jon.health)
The print statement outputs: 80
What you tried would work in another method within your class Hero:
class Hero(object):
def __init__(self, name, health=10):
self.name = name
self.health = health
self.alive = True
def take_damage(self):
self.health -= 5
if self.health <= 0:
self.alive = False
def is_alive(self):
return self.alive == True
If you are trying to reduce the health of an object of type Hero, you need to do it via the object reference like this:
my_hero = Hero()
my_hero.take_damage()
print(my_hero.is_alive())
Or you can access self.health directly (but better to do it via a method like I showed above):
my_hero = Hero()
my_hero.health -= 5

simple python text adventure game errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.

Crude virtual shop project fails when selection item from dictionary

I am making a crude shop in a Python 3.x script as a small project ( I started coding two days ago ), and when my program attempts to subtract the value of the item selected by the user from the initial amount of money the user starts out with, the program crashes.
Note: balance(): function aims to display remaining amount of money yet, but is not finished yet.
How can I fix my code, and is there any other way to improve/optimize it? Also, if you give a solution, please assume I don't know what method you will be using, so please give context and explain what you are using and other applications it can be used in.
import time
import sys
# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
# Money Values/Variables:
# Initial Money
initialMoney = 3000
# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order
def browse():
print("Welcome to the Virtual Shop Catalog")
time.sleep(1)
print("Here is what is currently on sale (item:price): ")
time.sleep(1)
print(shopCatalog)
time.sleep(1)
print("Enter '4' to quit")
time.sleep(1)
# This loop is where you choose to either return to the main menu, or order items.
while True:
try:
shopChoice = int(input("Enter item of choice: "))
if shopChoice == 4:
print("Returning back to main menu...")
time.sleep(0.5)
mainMenu()
break
# This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
elif shopChoice == 1 or 2 or 3 or 4 or 5 or 6:
print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
initialMoney = initialMoney - shopCatalog[shopChoice]
break
elif shopChoice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-6")
browse()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# Balance and money in account:
# This loop allows you to check the money in your account:
def balance():
print("hi")
# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.
def mainMenu ():
time.sleep(0.5)
print("1. Browse shop catalog")
time.sleep(0.5)
print("2. Check remaining balance")
time.sleep(0.5)
print("3. Quit program")
while True:
try:
choice = int(input("Enter number of choice: "))
if choice == 1:
browse()
break
elif choice == 2:
balance()
break
elif choice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-3")
mainMenu()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# On startup:
# This is the startup code and messages
print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()
Shop catalog is defined as:
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
However, you are trying to access the key by number. Such as
shopCatalog[2] which doesn't exist as a valid key. A valid key would be
shopCatalog['2. Gucci Belt']
Instead, try a list of tuples. A list is better because the order is guaranteed. In a dict, even though you numbered your items, it may print out of order.
shopCatalog = [ ('MCM Backpack', 790), ('Gucci Belt' : 450) , ...]
If you want the first item, you can just access it by the index. If you want them numbered, again, just use the index (although for both, keep in mind it is zero-indexed so you may have to add on to print your numbering and subtract one to get the right item.
Also, there is a flaw in your logic here:
shopChoice == 1 or 2 or 3 or 4 or 5 or 6:
While people talk like that, coding doesn't work like that. Instead, you'd have to do:
shopChoice ==1 or shopChoice ==2 and so on. But skip all of that and just say:
elif 1 <= shopChoice <= 6:
The error is:
Traceback (most recent call last):
File "C:/Users/s4394487/Downloads/crap.py", line 96, in <module>
mainMenu()
File "C:/Users/s4394487/Downloads/crap.py", line 73, in mainMenu
browse()
File "C:/Users/s4394487/Downloads/crap.py", line 38, in browse
print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
KeyError: 1
shopCatalog is a dictionary, so you can access its values using keys. The keys are '1. MCM Backpack', '2. Gucci Belt' etc. Not numbers.
If you want to access the first, second etc. values in a dictionary, you can use an OrderedDictionary in Python: https://docs.python.org/3/library/collections.html#collections.OrderedDict
Try the below code, now i think it will work:
import time
import sys
# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
# Money Values/Variables:
# Initial Money
initialMoney = 3000
# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order
def browse():
global initialMoney
print("Welcome to the Virtual Shop Catalog")
time.sleep(1)
print("Here is what is currently on sale (item:price): ")
time.sleep(1)
print(shopCatalog)
time.sleep(1)
print("Enter '4' to quit")
time.sleep(1)
# This loop is where you choose to either return to the main menu, or order items.
while True:
try:
shopChoice = input("Enter item of choice: ")
if shopChoice == 4:
print("Returning back to main menu...")
time.sleep(0.5)
mainMenu()
break
# This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
elif shopChoice in ('1','2','3','4','5','6'):
print(" Purchased 1 " + str(shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]) + " .")
initialMoney = initialMoney - shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]
break
elif shopChoice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-6")
browse()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# Balance and money in account:
# This loop allows you to check the money in your account:
def balance():
print("hi")
# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.
def mainMenu ():
time.sleep(0.5)
print("1. Browse shop catalog")
time.sleep(0.5)
print("2. Check remaining balance")
time.sleep(0.5)
print("3. Quit program")
while True:
try:
choice = int(input("Enter number of choice: "))
if choice == 1:
browse()
break
elif choice == 2:
balance()
break
elif choice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-3")
mainMenu()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# On startup:
# This is the startup code and messages
print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()
Your code didn't work because there are no such a key i.e 1 or 2 etc so i simply just check each key if shopChoice is in it, if it is, get the value of it, if it isn't, check the next one.

Categories