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")
Related
I decided that I would write a code to simulate a betting game, where you guess the number the dice will land on. Eventually, the code became a full-blown simulator, with credit-card withdrawals and different dice types and stakes (don't ask me why there's a 4-sided dice, I doubt it's possible).
Anyway, I kept getting the same error. This is my code:
import random
from random import randint
diea = randint(1,4)
dieb = randint(1,5)
diec = randint(1,6)
jackpot = randint(1,30)
chance = randint (1,30)
cquit = "a"
bal = 10
credcard = 100
withdrawal = 0
deposit = 0
if jackpot == chance:
print("You won the jackpot of 10k!")
bal = bal + 10000
while cquit.lower() == "a":
print ("Your balance is $", bal)
print ("Your credit card balance is $", credcard)
choicea = input("Would you like to deposit / withdraw money - a for deposit, b for withdrawal, anything else to skip: ")
if choicea.lower() == "a":
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
if deposit > bal:
print ("You do not have enough money - cancelling process")
else:
credcard = deposit + credcard
bal = bal - deposit
print ("Your balance is $", bal)
print ("Your credit card balance is", credcard)
if choicea.lower() == "b":
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
if withdrawal > credcard:
print ("Your card does not allow overdrafts - cancelling process")
else:
bal = withdrawal + bal
credcard = credcard - withdrawal
print ("Your balance is $", bal)
bet = int(input("How much would you like to bet?: "))
if bet > bal:
print ("You do not have enough money")
else:
diechoice = input("Choose die - A (1-4, x2), B (1-5, x3), C(1-6, x4): ")
if diechoice.lower() == "a":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - balance doubled")
bal = bal + bet
if guess > 4:
print ("That is above the die's capacity - bet cancelled")
if guess != diea:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "b":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - tripling balance")
bet = bet*2
bal = bal + bet
if guess > 5:
print ("That is above the die's capacity - bet cancelled")
if guess != dieb:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
if diechoice.lower() == "c":
guess = int(input("What will the die land on?: "))
if guess == diea:
print ("Correct guess - quadrupling balance")
bet = bet*3
bal = bal + bet
if guess > 6:
print ("That is above the die's capacity - cancelling bet")
if guess != diec:
print ("Incorrect guess - bet removed from balance")
bal = bal - bet
elif diechoice.lower() != "a" and diechoice.lower() != "b" and diechoice.lower() != "c":
print ("Incorrect input - skipping bet")
cquit = input("a to continue, anything else to end: ")
if cquit.lower() == "a":
if bal == 0 and credcard == 0:
print ("ending program - you are bankrupt")
cquit = "b"
if bal > 0:
print ("continuing program")
print ("...")
print ("...")
print ("...")
else:
print ("ending program")
This is the error I get in the code when testing it. It happens when I enter a or b on the first input statement whenever it loops:
Traceback (most recent call last):
File "D:\FAKE NEWS\du.py", line 30, in <module>
withdrawal = int(input("How much money would you like to withdraw - you have $", credcard," on your card"))
TypeError: input expected at most 1 arguments, got 3
I've been reading other reports on the same errors but I'm too bad at Python to understand any of it.
input() is not like print(), you can't give it multiple arguments and expect it to concatenate them automatically in the prompt.
You have to do the string formatting yourself.
withdrawal = int(input("How much money would you like to withdraw - you have $%.2f on your card" % (credcard)))
deposit = int(input("How much would you like to deposit - you have $" + str(bal) + " on you right now: "))
and
withdrawal = int(input("How much money would you like to withdraw - you have $"+ str(credcard) + " on your card"))
You're passing three arguments to input, but it only takes one.
To put a number into a string, use str.format:
prompt = "You have ${} on your card.".format(dollars)
input(prompt)
This inserts the value of dollars as the first "replacement field" ({}), formatting it by calling str. You can add multiple replacement fields, and you can name them like so:
"x is {}, y is {}".format(x, y)
"x is {1}, y is {0}".format(y, x) # note switched arguments
"x is {x} y is {y}".format(x=x, y=y)
If you are using Python 3.6 or later, you can use an f-string instead:
current_balance = 100;
f"You have ${current_balance} on your card."
There are many other things you can do with the string-formatting syntax. This answer provides a quick look at a few of them, if you don't want to read the documentation.
change input line from
deposit = int(input("How much would you like to deposit - you have $", bal," on you right now: "))
to
deposit = int(input("How much would you like to deposit - you have $"+str(bal)+" on you right now: "))
I want the user to pick an item from the shop and I want to use a loop to keep track of the prices(the value in the dictionary) to add up and keep a running total after every input from user. If the user inputs something that is not in the dictionary, it should say that it does not exist.
thanks in advance for help
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
for key, value in machine.items():
print(key,value)
print("------------------------------")
selection = input("Please choose the number of the item you would like to purchase: ")
total=0
for i in machine:
if selection=="1":
print("You chose shirt and your total is: $", machine["1.shirt: $"])
elif selection=="2":
print("You chose shirt and your total is: $", machine["2.pants: $"])
elif selection=="3":
print("You chose shirt and your total is: $", machine["3.sweater: $"])
elif selection=="4":
print("You chose shirt and your total is: $", machine["4.socks: $"])
elif selection=="5":
print("You chose shirt and your total is: $", machine["5.hat: $"])
else:
print("Your option does not exist. Your total is: ",total)
You should update the value of total every time a choice is made. See example below
def main():
machine= {"1.shirt: $":10, "2.pants: $":15, "3.sweater: $":20,"4.socks: $":5, "5.hat: $":7}
total=0
for key, value in machine.items():
print(key,value)
print("------------------------------")
while True: # Keep Looping
selection = input("Please choose the number of the item you would like to purchase: ")
if selection=="1":
total += machine["1.shirt: $"];
print("You chose shirt and your total is: $", total)
elif selection=="2":
total += machine["2.pants: $"];
print("You chose shirt and your total is: $", total)
else:
print("Your option does not exist. Your total is: ",total)
break
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()
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
I'm making a little application in python, but i have no idea what to do next.
#!/usr/bin/env python
print("Welcome to the store!")
price_list = [['apple', 'orange', 'grapefruit', 'bomb', 'gun'], [3, 2, 5, 15, 10]]
inventory = []
print("You can buy the following things")
print(price_list[0][0])
print(price_list[1][0], 'dollars')
print(price_list[0][1])
print(price_list[1][1], 'dollars')
print(price_list[0][2])
print(price_list[1][2], 'dollars')
print(price_list[0][3])
print(price_list[1][3], 'dollars')
print(price_list[0][4])
print(price_list[1][4], 'dollars')
budget = 20
buy = input("What would you like to buy? Type in one of the previous options to buy something You only have 20 dollars to spend though! ")
print("You bought", buy)
if budget >= 0:
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
if buy == 'orange':
print("It cost 2 dollars")
budget -= 2
inventory.append('orange')
print("Your inventory is below")
print(inventory)
if buy == 'grapefruit':
print("It cost 5 dollars")
budget -= 5
inventory.append('grapefruit')
print("Your inventory is below")
print(inventory)
if buy == 'bomb':
print("It cost 15 dollars")
budget -= 15
inventory.append('bomb')
print("Your inventory is below")
print(inventory)
if buy == 'gun':
print("It cost 10 dollars")
budget -= 10
inventory.append('gun')
print("Your inventory is below")
print(inventory)
I want to make it so i can add one thing, then be able to add another thing until i have reahed my budget, but if i use a while statement, it just keeps adding the thing i buy! help please!
Changing if budget >= 0 to while budget >= 0 is the right idea, you just have to move the request for user input into the while loop as well. That way it will ask for input, check it against the items in the shop, then if budget >= 0 it will do it again, starting with requesting more input.
#!/usr/bin/env python
print("Welcome to the store!")
setup_price_list() #pseudocode
budget = 20
while budget >= 0:
buy = input("What would you like to buy?")
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
#the rest of the if statements
print("You bought", buy)
print("Your inventory is below")
print(inventory)
Once you have got that working, I suggest you take a look at the Python Data Structure called a dictionary. It can make code like this much simpler, for example:
print("Welcome to the store!")
price_list = {'apple':3, 'orange':2, 'grapefruit':5, 'bomb':15, 'gun':10}
print("You can buy:")
for key in price_list:
item = key
price = price_list[key]
print(item, price)
budget = 20
while budget > 0:
buy = raw_input("What do you want to buy?")
price = price_list[buy] #You will get an error if you give it a key it doesn't have
budget -= price
print("You bought: ", buy)
print("It costed: $", price)
Oh and you may want to add in a check to see whether you actually have enough money left to buy the item before you buy it, else you can still buy anything as long as you aren't in debt, I'll leave that to you to figure out :)