Python Breakfast Item Menu issue - python

I'm new to python so in advance, Please excuse the lack of knowledge that may be present.
I'm working on a simple Breakfast Menu Items list. of course there are many ways of handling this, I've chosen this way. A "beginners" way. Below is the code I'm using. When it get's to the Toppings section, receives the input. It goes to the print() method and crashes due to "Meal" not being defined. I ran the debugger via Python which helps me understand what is going on. after the input value is received and runs thru the if elif else statement, why won't the value "stay put" long enough to return the whole value of all 3 selections? Thanks in Advance....
I'm still learning; eventually there will be other statements that'll provide other options, if I choose something outside the options, a function will happen.
If I choose just 2 or 1 of the options, the output will show. For now, this is giving me an issue. Please Please Please Pleaseeeeeee I need help, fellow student to teachers.
# ACTUAL CODE BEING USED
print("1. Eggs")
print("2. Pancakes")
print("3. Waffles")
print("4. OatMeal")
MainChoice = int(input("Choose a breakfast item #: "))
if(MainChoice == 1):
Meal = "Eggs"
print("You've Choosen eggs")
elif (MainChoice == 2):
Meal = "Pancakes"
print("You've Choosen pankcakes")
elif (MainChoice == 3):
Meal = "Waffles"
print("You've Choosen waffles")
else:
print("You've Choosen Oatmeal")
if (MainChoice <= 4):
print("1. Wheat Toast")
print("2. Sour Dough")
print("3. Rye Toast")
print("4. White Bread")
Bread = int(input("Choose a type of bread: "))
elif (Bread == 1):
print("You chose " + Meal + " with wheat toast.")
elif (Bread == 2):
print("You chose " + Meal + " with sour dough.")
elif (Bread == 3):
print("You chose " + Meal + " with rye toast.")
elif (Bread == 4):
print("You chose " + Meal + " with pancakes.")
else:
print("We have eggs, but not that kind of bread.")
if ((MainChoice >= 1) or (MainChoice <= 3)):
print("1. Syrup")
print("2. Strawberries")
print("3. Powdered Sugar")
Topping = int(input("Choose a topping: "))
if (Topping == 1):
print ("You chose " + Meal + " with and syrup and Bread.")
elif (Topping == 2):
print ("You chose " + Meal + " with and strawberries Bread.")
elif (Topping == 3):
print ("You chose " + Meal + " with and powdered sugar Bread.")
else:
print ("We have " + Meal + ", but not that topping Bread.")
if (MainChoice == 4):
print("You chose oatmeal.")
else:
print("Thank You for coming by and Eatting with us!")
ERR MESSAGE IF CHOSEN OATMEAL AND OTHER ITEMS:
AFTER SELECTION OF OATMEAL ITEM, WHEN SELECTION OF OTHER ITEMS,
ERROR MESSAGE OCCUR
OUT VIA PYTHON
Eggs
Pancakes
Waffles
OatMeal
Choose a breakfast item #: 4
You've Choosen Oatmeal
Wheat Toast
Sour Dough
Rye Toast
White Bread
Choose a type of bread: 1
Traceback (most recent call last):
File "/Users/(admin_name/Desktop/FOLDER/Breakfast-Menu.py", line 25, in
print("You chose " + Meal + " with wheat toast.")
NameError: name 'Meal' is not defined
OUTPUT IF CHOSEN EVERYTHING # 1
Eggs
Pancakes
Waffles
OatMeal
Choose a breakfast item #: 1
You've Choosen eggs
Wheat Toast
Sour Dough
Rye Toast
White Bread
Choose a type of bread: 1
You chose Eggs with wheat toast.
Syrup
Strawberries
Powdered Sugar
Choose a topping: 1
You chose Eggs with and syrup and Bread.
Thank You for coming by and Eatting with us!
Also How do I get the bread to show up with the selection of Meal, I understand the Meal value is the user input, after the 1 and 2nd selection, grabbing the third, how is the value of all 3 selections stored into Meal to output the selection at the end? If I'm asking this correctly.

Take a look at what happens when MainChoice is 4 - only one of the conditional statements are executed, and in this case it's the else statement. None of the code under the if or elif statements gets executed, just the code under else. As such, there is no point in your program (when the input is 4) that the variable Meal is defined.
You need to add a definition of the Meal variable within the else statement for your code to work, so that when input is 4, Python actually has a value to use as the Meal variable.
Hope this helps.

When you choose OatMeal, you didn't set anything for the Meal variable.
Unlike your 1, 2, 3 options where you set a Meal.
print("1. Eggs")
print("2. Pancakes")
print("3. Waffles")
print("4. OatMeal")
MainChoice = int(input("Choose a breakfast item #: "))
if(MainChoice == 1):
Meal = "Eggs" # Meal Set!
print("You've Choosen eggs")
elif (MainChoice == 2):
Meal = "Pancakes" # Meal Set!
print("You've Choosen pankcakes")
elif (MainChoice == 3):
Meal = "Waffles" # Meal Set!
print("You've Choosen waffles")
else:
# No Meal set :c
print("You've Choosen Oatmeal")
if (MainChoice <= 4):
print("1. Wheat Toast")
print("2. Sour Dough")
print("3. Rye Toast")
print("4. White Bread")
Bread = int(input("Choose a type of bread: "))
elif (Bread == 1):
print("You chose " + Meal + " with wheat toast.")
elif (Bread == 2):
print("You chose " + Meal + " with sour dough.")
elif (Bread == 3):
print("You chose " + Meal + " with rye toast.")
elif (Bread == 4):
print("You chose " + Meal + " with pancakes.")
else:
# No Meal called
print("We have eggs, but not that kind of bread.")

Most persons have answered your direct question over why "Meal" is not defined, but I noticed some other things in the code. I'm going to make a few assumptions:
If no bread is selected, then no toppings for bread can be selected. In the options for toppings, you print that the topping is on a bread, but in the breads you allow for no bread to be selected.
If a bread is selected, when choosing the topping, the topping should be listed as being on the bread.
If oatmeal is selected, then you neither want bread, nor a topping. The 'if' statement before toppings will list the toppings no matter what (I think you want an 'and', not an 'or'). But regardless whether the toppings are displayed, the customer is asked to choose a topping. I believe this to a be a formatting issue.
In the statement, "We have eggs, but not that kind of bread.", I believe it should have been "We have " + Meal + ", but not that kind of bread.". I base this on the similar statement found after the toppings selection.
All this being said, I rewrote the code using an object oriented approach. This was not meant so much to answer your question, but to put out a different way of going about this.
UNDEFINED = "undefined"
class Selections:
def __init__(self, statement, *args):
self._items = args
self._response = statement
self._defaultResponse = UNDEFINED
def setDefault(self, statement):
self._defaultResponse = statement
def makeSelection(self):
for index, value in enumerate(self._items):
print(str(index + 1) + ". " + value)
selectedMeal = input("Please choose a breakfast item (by number): ") - 1
if selectedMeal > len(self._items):
if (self._defaultResponse != UNDEFINED):
print(self._defaultResponse)
self.last = UNDEFINED
return
selectedMeal = len(self._items) - 1
self._printResponse(self._items[selectedMeal])
self.last = self._items[selectedMeal]
def _printResponse(self, item):
print(self._response.format(item))
mainSelection = Selections("You've Choosen {}",
"Eggs", "Pancakes", "Waffles", "OatMeal")
mainSelection.makeSelection()
if (mainSelection.last != "OatMeal"):
breadSelection = Selections(
"You chose " + mainSelection.last + " with {}.",
"Wheat Toast", "Sour Dough", "Rye Toast", "White Bread")
breadSelection.setDefault(
"We have {}, but not that kind of bread".format(mainSelection.last))
breadSelection.makeSelection()
if (breadSelection.last != UNDEFINED):
toppingSelection = Selections(
"You chose " + mainSelection.last + " with {} on " + breadSelection.last,
"Syrup", "Strawberries", "Powdered Sugar")
toppingSelection.setDefault(
"We have {} and {}, but not that kind of topping".format(
mainSelection.last, breadSelection.last))
toppingSelection.makeSelection()

Related

Beginner programmer, functions not working

beginner here, im currently creating a coffee shop program in pycharm where the costumer inputs the product and then the program sums up all of the price. Im trying to loop the program with the use of functions so the customer can order a many as they want. But when i inputted def main(): in the program, the program under the function does not continue when i run it and i made sure that the codes under the function are indented. Any help would be appreciated thanks enter image description here
here's the code, sorry
print("Good day!, welcome to Avenida's coffee shop")
print("Before i take you order, may i know your name?")
name = input("Input name here: ")
print(
"Hello there " + name + "!, to get started we sell different kinds of food here, we sell coffee, frappe, cake, and pastas")
print("To access our menu, input your preferred food below")
def main():
total_price = 0
category = input("Input your preferred food here: ")
if category.lower() == "coffee":
print("Coffee Menu:")
print("1 Cappuccino = $2")
print("2 Espresso = $2.50")
print("3 Latte = $3")
coffee_input = input("Input the assigned number of the coffee that you would like to order: ")
if int(coffee_input) == 1:
print("How many cappuccino would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 2
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
if int(coffee_input) == 2:
print("How many espresso would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 2.50
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
if int(coffee_input) == 3:
print("How many latte would you like to order?")
coffee_quantity = input("Input here: ")
coffee_total = float(coffee_quantity) * 3
print("That would be $" + str(coffee_total))
total_price = total_price + coffee_total
Try adding this to the end of your code, outside of your main loop. You defined a function called main, but you did not execute it, thus the issue.
if __name__ == '__main__':
main()

Multiple errors in my python school project [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
So, for my school project, that's due tomorrow, I was tasked with making a simple game from if statements. That is exactly what I tried doing, but whenever I run the game and try buying something else other than tomatoes, I still end up buying tomatoes. I don't know what I did wrong, so I am hoping someone can help me.
I'm really new to coding so I'm sorry if this is an annoying question or anything like that.
Here is the code:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
if input("Would you like to enter? Y/N ") == 'Y' or 'y': #go into the shop
print("You entered the shop.")
if input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'tomatoes' or 'Tomatoes' or 'tomato' or 'Tomato' or 't' or 'T': #choose to buy tomatoes
sum = int(money) - 5
print("You bought tomatoes. You have " + str(sum) + " dollars left.") #end balance if you choose tomatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'potatoes' or 'Potatoes' or 'potato' or 'Potato' or 'p' or 'P': #choose to buy potatoes
sum = int(money) - 7
print("You bought potatoes. You have " + str(sum) + " dollars left.") #end balance if you choose potatoes
elif input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ") == 'cucumbers' or 'Cucumbers' or 'cucumber' or 'Cucumber' or 'c' or 'C': #choose to buy cucumbers
sum = int(money) - 10
print("You bought cucumbers. You have " + str(sum) + " dollars left.") #end balance if you choose cucumbers
if input("Would you like to enter? Y/N ") != 'Y' or 'y': #don't go into the shop
print("You turned around and walked away from the shop.\n")
Thanks. Hope you can help me.
As already said, there are multiple issues with your code.
First, as already mentioned, input() == 'Y' or 'y' does not work. You need to use input().lower() == 'y', or input() in ['y','Y']. You should definately use this list method in your later checks, as it shortens your if clauses a lot.
Second, using buit in function names as a variable name is never a good idea, because you can't use the function later on.
Third, mind your indentation. You don't need to indent code more for every if statement, you can just indent it the same.
Fourth, you should not convert your money variable to int every time, as it is already int.
Fifth, you should save the result of your inputs into variables. Now, if the user types in patatoes in the first input, then there will be asked him another time what he wants to buy instead of the user being noticed that he just buyed patatoes.
I would suggest the following:
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
tobuy=input("You are at the vegetables isle. Do you want to buy tomatoes, ($5) potatoes ($7) or cucumbers? ($10) ")
if tobuy.lower() in ["tomatoes","tomato","t"]: #choose to buy tomatoes
balance = money - 5
print("You bought tomatoes. You have " + str(balance) + " dollars left.") #end balance if you choose tomatoes
elif tobuy.lower() in ["patatoes","patato","p"]: #choose to buy potatoes
balance = money - 7
print("You bought potatoes. You have " + str(balance) + " dollars left.") #end balance if you choose potatoes
elif tobuy.lower()in ["cumcumbers","cumcumber","c"]: #choose to buy cucumbers
balance = money - 10
print("You bought cucumbers. You have " + str(balance) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
In the following example, the user is asked what he wants to buy every time again, such that he can buy multiple things. Do also notice that you should change the original money variable instead of creating a new one, such that his money decreases every time he buys something.
money = 50 #Money that is in the players pocket
print("Welcome to our Shop!")
print("You have " + str(money) + " dollars in your wallet.") #starting balance
yn=input("Would you like to enter? Y/N ")
if yn.lower() == 'y': #go into the shop
print("You entered the shop.")
print("You are at the vegetables isle.")
if input("Do you want to buy tomatoes($7)?").lower()=='y': #choose to buy tomatoes
money = money - 5
print("You bought tomatoes. You have " + str(money) + " dollars left.") #end balance if you choose tomatoes
if input("Do you want to buy potatoes ($7)").lower() == 'y': #choose to buy potatoes
money = money - 7
print("You bought potatoes. You have " + str(money) + " dollars left.") #end balance if you choose potatoes
if input("Do you want to buy cucumbers? ($10) ").lower() == 'y': #choose to buy cucumbers
money = money - 10
print("You bought cucumbers. You have " + str(money) + " dollars left.") #end balance if you choose cucumbers
else: #don't go into the shop
print("You turned around and walked away from the shop.\n")
from dataclasses import dataclass
from typing import List
#dataclass
class Product:
name: str
plural: str
price: int
key: chr
def __str__(self):
return f'{self.plural}, (${self.price})'
#dataclass
class Customer:
money: int
products: List[Product]
def buy(self, p: Product):
self.money -= p.price
self.products.append(p)
print(f'You bought {p.name}. You have {self.money} dollars left.')
def enter(self, s):
print("You entered the shop.")
s.vegetables_isle(self)
#dataclass
class Shop:
products: List[Product]
def vegetables_isle(self, c: Customer):
print("You are at the vegetables isle.")
print("Do you want to buy", end=' ')
for p in self.products[:-1]: print(p, end = ' ')
print(f'or {self.products[-1]}')
answer = input('choice: ')
for p in self.products:
if answer.lower() in [p.name, p.plural, p.key]:
return c.buy(p)
if __name__ == '__main__':
shop = Shop(products = [
Product(name='tomato', plural='tomatoes', price=5, key='t'),
Product(name='potato', plural='potatoes', price=7, key='p'),
Product(name='cucumber', plural='cucumbers', price=10, key='c'),
])
customer = Customer(50, products=[])
choice = input("Would you like to enter? Y/N ")
if choice.lower() == 'y':
customer.enter(shop)
else:
print("You turned around and walked away from the shop.\n")

Part of code not executing (no errors shown)

This is a chatbot, that includes a choose your own adventure game, however if you select the 2nd option for the first choice (explore the beach) it doesn't execute anything after that in the game.
When I select the first option, everything works fine, so I don't understand why it's not showing. The game itself works fine if I run it separately from the chatbot, and I've checked the indenting already. Please help.
import random
#Choose YOur Own Adventure Game ========================================
print("Would you like to play a Choose Your Own Adventure game?\n")
game1 = input("Play a Choose YOur Own Adventure Game? ")
if (game1 == "Yes" or game1 == "yes"):
print("Alright! Let's get started...")
countdown = 5
while (time > 0):
print (("...") + str(time) + ("..."))
time = time - 1
print("Loading Game... 3, 2, 1..\n")
print("Welcome player!")
print("Hello " + name + ", welcome to this adventure game!\n")
print("You find yourself in a strange hut, in a dazed state. \nWhere am I? you wonder.")
print("You see lots of light near the door, & when you walk out you see... ")
print("... wow, so much sand!\n")
drown = random.randint(1,2)
help = random.randint(1,2)
#============================ Story starts here ========================================================
print("Turns out you're on a beach,\nYou don't know how you got here.")
print("The messy hut isn't too far from the shore.")
print("You walk onto the white sand, it's hot,\nand it seems like there's no one around.\n")
print("Weird, so you decide to look around.")
print("Maybe you can find some info on how you got here.\n")
#===================================Choice 1 =====================================
print("Do you want to examine the hut for clues or explore the beach?")
print("1: Examine the hut\n2: Explore the beach\n")
explore = int(input("Examine the hut or explore the beach?"))
while (explore < 1 or explore > 2):
print("Please enter 1 or 2.\n")
explore = int(input("Examine the hut or explore the beach?"))
if (explore == 1):
print("You go back into the hut.")
print("Near the door you notice something glistening.")
print("You walk over and decide to take a closer look.")
#========================================= Choice 2 ====================================
print("You find a small clear vial with some mysterious liquid in it.")
print("I should:\n1: Drink it.\n2: Just put in my pocket.\n")
drink =int(input("Drink it or save for it later?"))
while (drink < 1 or drink > 2):
print("Please enter either 1 or 2.\n")
drink =int(input("Drink it or save for it later?"))
#=========================================== Choice 3 =========================================
if (drink == 2):
print("You put it in your pocket.\n")
print("There's nothing else in the hut.")
print("You then go back onto the beach.")
print("You go for a walk near the water.")
print("You don't find anything interesting.")
print("You decide to go for a swim.")
print("The water envelopes you, and you drown.")
print("Game Over.")
print("This is one of the 8 endings thanks for playing!")
if (drink == 1):
print("You drink the whole bottle, it made you feel weird.")
print("All of a sudden you feel drowsy.")
print("Do you want to take a nap to feel refreshed?")
print("1: Yes\n2: No\n")
nap = int(input("Want to take a nap?"))
while (nap < 1 or nap > 2):
print("Enter 1 or 2")
nap = int(input("Do you want to take a nap to feel refreshed?"))
if(nap == 1):
print("You decide to doze off...\n")
naptime =int(input("How long you want to sleep for?(in hours)"))
if (naptime < 3):
print("You took a short nap.\n When you woke up you decided to go relax on the beach.")
print("The water looks cold, just what you need on a hot day like this.")
print("You decide to go for a swim.\n")
print("Some time later...\n")
if (drown == 1):
print("While in the water,a strong current swept you away from the shore, \nyou're not a great swimmer, so you drowned.")
print("This is one of the 8 endings, thanks for playing!")
if (drown == 2):
print("Exhausted from swimming, you lay down on the sand to rest.")
print("You were never good with puzzles or survival,\nit doesn't seem like theres a way to get off this island.\n")
print("Do you want to give up on the thought of escaping?")
print("1: Yes\n2: No")
give_up = int(input("Give up on escaping?"))
while (give_up < 1 or give_up > 3):
print("Enter 1 or 2")
if (give_up == 1):
print("You gave up on escaping the island.")
print("Without food or water you slowly waste away.")
print("You died, not knowing where you are or how you got there.\n")
print("This is one of the 8 endings, thanks for playing!")
if (give_up == 2):
print("You decide to keep looking for an exit.")
print("After a few days it feels like you've searched every nook and cranny.")
print("You don't find anything.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
#========================================== Ending A ================================================
if (naptime > 3):
print("'Hey! Get up! You've been voted off'\nyou hear a man's voice shout")
print("(a few minutes later)\nApparently this is one of those game shows, y'know like Survivor")
print("Watching me sleep for so long was too boring, so I have been kicked off.")
print("This is one of the 8 endings, thanks for playing!")
if(nap == 2):
print("Everything became hazy, as you stagger onto the hot sand.")
print("Everything goes black as you fall straight into the water.\n")
print(name + " wake up! Are you alright?")
print("Huh? Oh... it's just an interesting dream.")
print("Whew, what a weird nightmare... you sigh.")
print("This is one of the 8 endings, thanks for playing!")
#============================================ If you explore the beach =========================================
if (explore == 2):
print("You decide to go for a walk near the water.")
print("You don't find anything out of the ordinary, it's just a beach.")
print("Do you want to relax on the beach?")
print("1: Yes\n2: No\n")
relax = int(input("Relax?"))
while (relax < 1 or relax > 2):
print("Enter 1 or 2")
relax = int(input("Relax?"))
if (relax == 1):
print("You laid down on the sand.")
print("You fall asleep.")
print("Thump, thump, .... THUD\n")
print("You open your eyes,everything is shaking.")
print("It's, it's... an earthquake!")
print("The raggedy hut collapses, any clues that might've been there are destroyed.\n")
print("You go examine the remains of the hut.")
print("Within the sand you find a flare gun!")
print("You use it, and a ship picks you up.")
print("You've escaped!")
print("This is one of the 8 endings, thanks for playing!")
if (relax == 2):
print("With nothing else to do you go back into the hut.\n")
print("Upon further examination you see a small vial full of some liquid.")
print("The liquid is clear and odorless.")
print("I should:\n1: Drink it.\n2: Just put in my pocket.\n")
drink =int(input("Drink it or save for it later?"))
if(drink == 1):
print("You're not sure what you just drank, but one thing's for sure,")
print("you are probably going to faint.")
print("Everything goes black...\n")
print("Hey! Wake up!")
print("You wake up to see two lifeguards standing over you.")
print("You passed out from dehydration, and everything was just a hallucination.")
print("This is one of the 8 endings, thanks for playing!")
if(drink == 2):
print("You put it in your pocket.")
print("You are no closer to escaping than before.\n")
print("All of a sudden you catch a glimpse of ship passing by!")
print("Maybe if they hear you you can catch a ride off this island!\n")
print("Do you want to call out to them?")
print("1: Yes\n2: No\n")
scream = int(input("Try asking for help?"))
if(scream == 1):
if(help == 1):
print("Your screams were successful!")
print("You are saved!")
print("This is one of the 8 endings, thanks for playing!")
if(help == 2):
print("Whoever was on the ship didn't seem to hear you.")
print("It seems like there's nothing you can do.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
if(scream == 2):
print("Nobody comes to your rescue.")
print("You are trapped, and without any food or water you slowly perish.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
while (scream < 1 or scream > 2):
print("Enter 1or 2.\n")
scream =int(input("Try asking for help?"))
while (drink < 1 or drink > 2):
print("Please enter either 1 or 2.\n")
drink =int(input("Drink it or save for it later?"))
#End of Game ===============================================================
elif (game1 == "No" or "no"):
print("Oh, I see you don't want to play...")
print("How sad, I spent all that time setting it up for you ;(")
print("Oh well, I guess we won't play.\n")
The problem with your code is you have put the statement if explore == 2 inside the if explore == 1. Python gives a lot of importance to indentation. All you need to do is indent the second if statement with the first one. In your code.
Sample:
x=2
if x==1:
if x==2:
body....
This is the sample of your statement. Here, x=2. First it checks if x==1. If no then goes to other statement. But you have defined if x==2 inside the first one. So it will be executed only if the first statement is True.
So the correct expression is:
x=2
if x==1:
body....
elif x==2:
body....
This is the case in your code.
if (explore == 1):
print("You go back into the hut.")
print("Near the door you notice something glistening.")
print("You walk over and decide to take a closer look.")
#========================================= Choice 2 ====================================
print("You find a small clear vial with some mysterious liquid in it.")
print("I should:\n1: Drink it.\n2: Just put in my pocket.\n")
drink =int(input("Drink it or save for it later?"))
while (drink < 1 or drink > 2):
print("Please enter either 1 or 2.\n")
drink =int(input("Drink it or save for it later?"))
#=========================================== Choice 3 =========================================
if (drink == 2):
print("You put it in your pocket.\n")
print("There's nothing else in the hut.")
print("You then go back onto the beach.")
print("You go for a walk near the water.")
print("You don't find anything interesting.")
print("You decide to go for a swim.")
print("The water envelopes you, and you drown.")
print("Game Over.")
print("This is one of the 8 endings thanks for playing!")
if (drink == 1):
print("You drink the whole bottle, it made you feel weird.")
print("All of a sudden you feel drowsy.")
print("Do you want to take a nap to feel refreshed?")
print("1: Yes\n2: No\n")
nap = int(input("Want to take a nap?"))
while (nap < 1 or nap > 2):
print("Enter 1 or 2")
nap = int(input("Do you want to take a nap to feel refreshed?"))
if(nap == 1):
print("You decide to doze off...\n")
naptime =int(input("How long you want to sleep for?(in hours)"))
if (naptime < 3):
print("You took a short nap.\n When you woke up you decided to go relax on the beach.")
print("The water looks cold, just what you need on a hot day like this.")
print("You decide to go for a swim.\n")
print("Some time later...\n")
if (drown == 1):
print("While in the water,a strong current swept you away from the shore, \nyou're not a great swimmer, so you drowned.")
print("This is one of the 8 endings, thanks for playing!")
if (drown == 2):
print("Exhausted from swimming, you lay down on the sand to rest.")
print("You were never good with puzzles or survival,\nit doesn't seem like theres a way to get off this island.\n")
print("Do you want to give up on the thought of escaping?")
print("1: Yes\n2: No")
give_up = int(input("Give up on escaping?"))
while (give_up < 1 or give_up > 3):
print("Enter 1 or 2")
if (give_up == 1):
print("You gave up on escaping the island.")
print("Without food or water you slowly waste away.")
print("You died, not knowing where you are or how you got there.\n")
print("This is one of the 8 endings, thanks for playing!")
if (give_up == 2):
print("You decide to keep looking for an exit.")
print("After a few days it feels like you've searched every nook and cranny.")
print("You don't find anything.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
#========================================== Ending A ================================================
if (naptime > 3):
print("'Hey! Get up! You've been voted off'\nyou hear a man's voice shout")
print("(a few minutes later)\nApparently this is one of those game shows, y'know like Survivor")
print("Watching me sleep for so long was too boring, so I have been kicked off.")
print("This is one of the 8 endings, thanks for playing!")
if(nap == 2):
print("Everything became hazy, as you stagger onto the hot sand.")
print("Everything goes black as you fall straight into the water.\n")
print(name + " wake up! Are you alright?")
print("Huh? Oh... it's just an interesting dream.")
print("Whew, what a weird nightmare... you sigh.")
print("This is one of the 8 endings, thanks for playing!")
#============================================ If you explore the beach =========================================
elif (explore == 2):
print("You decide to go for a walk near the water.")
print("You don't find anything out of the ordinary, it's just a beach.")
print("Do you want to relax on the beach?")
print("1: Yes\n2: No\n")
relax = int(input("Relax?"))
while (relax < 1 or relax > 2):
print("Enter 1 or 2")
relax = int(input("Relax?"))
if (relax == 1):
print("You laid down on the sand.")
print("You fall asleep.")
print("Thump, thump, .... THUD\n")
print("You open your eyes,everything is shaking.")
print("It's, it's... an earthquake!")
print("The raggedy hut collapses, any clues that might've been there are destroyed.\n")
print("You go examine the remains of the hut.")
print("Within the sand you find a flare gun!")
print("You use it, and a ship picks you up.")
print("You've escaped!")
print("This is one of the 8 endings, thanks for playing!")
if (relax == 2):
print("With nothing else to do you go back into the hut.\n")
print("Upon further examination you see a small vial full of some liquid.")
print("The liquid is clear and odorless.")
print("I should:\n1: Drink it.\n2: Just put in my pocket.\n")
drink =int(input("Drink it or save for it later?"))
if(drink == 1):
print("You're not sure what you just drank, but one thing's for sure,")
print("you are probably going to faint.")
print("Everything goes black...\n")
print("Hey! Wake up!")
print("You wake up to see two lifeguards standing over you.")
print("You passed out from dehydration, and everything was just a hallucination.")
print("This is one of the 8 endings, thanks for playing!")
if(drink == 2):
print("You put it in your pocket.")
print("You are no closer to escaping than before.\n")
print("All of a sudden you catch a glimpse of ship passing by!")
print("Maybe if they hear you you can catch a ride off this island!\n")
print("Do you want to call out to them?")
print("1: Yes\n2: No\n")
scream = int(input("Try asking for help?"))
if(scream == 1):
if(help == 1):
print("Your screams were successful!")
print("You are saved!")
print("This is one of the 8 endings, thanks for playing!")
if(help == 2):
print("Whoever was on the ship didn't seem to hear you.")
print("It seems like there's nothing you can do.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
if(scream == 2):
print("Nobody comes to your rescue.")
print("You are trapped, and without any food or water you slowly perish.")
print("Game Over.")
print("This is one of the 8 endings, thanks for playing!")
while (scream < 1 or scream > 2):
print("Enter 1or 2.\n")
scream =int(input("Try asking for help?"))
while (drink < 1 or drink > 2):
print("Please enter either 1 or 2.\n")
drink =int(input("Drink it or save for it later?"))

Text-based game stats

I'm working on a mini-project I'm doing for fun to practice python skills and I am stuck on a problem I can't seem to figure out. I have a function that gives me the default stats for every class in the game and I want it to change depending on what class/weapon I choose in the beginning. I am still trying to learn functions so any input will be valuable. So gameStat() is the default stats while gameStat() is the changed one.
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:")
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=input("What class would you like to play?\n:")
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :"))
print(baseStats(character,weapon))
Thank you so much.
When you take any input it will be in string format to compare it with an integer you need to convert it to integer using int() function
I modified the code and it returns the value of "mana" or "magic" correctly
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=int(input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:"))
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=int(input("What class would you like to play?\n:"))
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(int(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :")))
print(baseStats(userClass,weapon))
In the gameState() function the baseStats takes 5 argument but when you defined baseStats it only takes two arguments character and weapon which is confusing.

Text-based adventure in Python 3

I'm working on a text-based RPG, but I've found numerous problems, like:
being unable to go anywhere after entering the shop;
I cannot access the "tavern" for some reason; and
the computer just says "buy is not defined in crossbow".
Code:
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.")
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")
The first time you ask the user where to go on line 111, what happens if they enter something besides "shop"? then the if choice == "shop": condition on line 119 will fail, and buy = input("...") will never execute. At that point, buy doesn't exist, so when the next conditional executes, it crashes because it can't evaluate if buy == "crossbow". buy has no value, so you can't compare it to anything.
You need to indent all of your shop logic so that it lies inside the if choice == "shop" block.
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")
#...etc
if buy == "spell":
print("this costs 35 gold")
And the same problem is present for your tavern code. Even if you don't go to the tavern, you check for tavernChoice. That needs to be indented as well.
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.")
At this point, your program will end, but I'm guessing you want to continue to be able to explore areas. You could put everything in a while loop, starting with the first input command.
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: ")
if choice == "shop":
print("Welcome to the shop!")
#...etc
elif choice == "tavern":
print("You enter the tavern...")
#...etc
elif choice == "forest":
print("You enter the forest...")
#etc
else:
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
This is also a little cleaner than your current method, since you only have to ask the user where they're going once, instead of three times on lines 112, 165, and 170.
Building on Kevin's answer, here is a version with redundancy squeezed out, so you can add a new place just by adding a new def go_xyz(): ... near the top.
def go_shop():
print("Welcome to the shop!")
#...etc
def go_tavern():
print("You enter the tavern...")
#...etc
def go_forest():
print("You enter the forest...")
#etc
places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)
inventory = ['book']
retry = False
while True:
if not retry:
print("Here is your inventory: ", inventory)
else:
print("I do not know that place")
print("Where do you wish to go?")
print("Possible places: ", placenames, '.')
choice = input("? ")
try:
places[choice]()
retry = False
except KeyError:
retry = True

Categories

Resources