This is supposed to be code for a system in a store that loops again and again if someone wants to buy something else. Please help.
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0:
print(x)
continue
elif other=="no":
x+1
else:
print("Error")
The last part doesn't work- can someone fix it so it does? This is Python 3- thanks.
problem fixed & loop optimized -
the problem you encountered was the extra brackets () around your input-function.
the loop is now optimized because your whole buying cycle is now inside this while True: loop. it will be repeated again and again until the user inputs something different then "yes" at the other question.
while True:
menu=["apple","water","juice"]
apple=50
water=80
juice=100
money=int(input("How much money in pennies do you have?"))
if money>=100:
print("We have the following items you can buy: apple, water, juice")
elif money>=80 and money<=100:
print("We have the following items you can buy: apple, water")
elif money>=50 and money<=80:
print("We have the following item you can buy: apple")
else:
print("Sorry, you can't buy anything.")
buy=input("What do you want to buy?")
if buy=="apple":
print("You have",money-50)
elif buy=="water":
print("You have",money-80)
else:
print("You have",money-100)
other=input("Do you want to buy anything else?")
if other=="yes":
continue
else:
break
other=(input("Do you want to buy anything else?"))
if other=="yes":
while x=0: <-- should use x==0, but x is not declared
print(x) <-- wrong indentation
continue
elif other=="no":
x+1 <-- even if x was declared, this only sum and nothing
else: more (nothing changes in your program)
print("Error")
This last part basically does nothing useful even if it worked. I suggest you to use the code posted in the other answer.
Related
I am currently writing a Tipper program for the job, and I am having a lot of issues with it. The result keeps saying invalid syntax, and I have switched up so many things but it seems like I can never make it just right. To give you an example of this, here is my current code:
print("Now that your belly is full, how much is the fee?")
fee = input("Enter your fee: ")
print("Would you like to give us a tip?")
answer = input("Yes or no?")
if answer == no:
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == yes:
tip = input("Would you like to tip 15 percent or 20 percent? ")
if tip == 15 :
cost1 = fee/15 + fee
elif tip == 20 :
cost2 = fee/20 + fee
else:
print("I do not understand.")
else:
print("I do not understand.")
print:("Have a wonderful day!")
So, yeah, to be honest with you I am not sure why it is not working, but could someone please answer? I am really stumped by this.
I fixed the bugs in your code and tested it, however the overall code structure can still be improved.
So what caused your program to crash?
"No" and "Yes" are both strings so you have to put them between " "
You have to convert the fee entered from the user to integer using int() function so that you can do math calculations on it.
You were calculating the tip wrongly, I fixed it using these calculations
15% >> Total = 1.15xfee
20% >> Total = 1.20xfee
Note: in the below code I used the math.ceil() function to round up the tip to a whole number.
To improve the user experience a bit, I also added a line that prints the total cost, including the tip, back to the user.
Here is the corrected code:
import math
print("Now that your belly is full, how much is the fee?")
fee = int(input("Enter your fee: "))
print("Would you like to give us a tip?")
answer = input("yes or no?")
if answer == "no":
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == "yes":
tip = int(input("Would you like to tip 15 percent or 20 percent? "))
if tip == 15 :
cost = math.ceil(1.15 * fee)
print("Your total, including fee is, ", cost)
elif tip == 20 :
cost = math.ceil(1.20 * fee)
print("Your total, including fee is, ", cost)
else:
print("I do not understand.")
else:
print("I do not understand.")
print("Have a wonderful day!")
Here is a version that works. Now, there are still problems. First, it doesn't catch if they enter garbage that is not a number for the bill or for the tip. Second, it doesn't round the tip, because I don't know what currency you're using. But at least you can run this and get an answer.
print("Now that your belly is full, how much is the bill?")
fee = float(input("Enter your bill: "))
print("Would you like to give us a tip?")
answer = input("yes or no?")
if answer.lower() == 'no':
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand.")
elif answer.lower() == "yes":
tip = int(input("What tip percentage do you use? "))
fee += fee * tip / 100
else:
print("I do not understand.")
print("Your total bill is", fee)
As mentioned in the comments, you need to wrap the answers you're testing for in quotes (double quotes ", or single quotes ' will do), because otherwise python will think they are variable names and not string literals, that you want to compare against.
Also, in the last print, you have a colon (:) that doesn't belong there.
Here is your code with those two issues fixed.
print("Now that your belly is full, how much is the fee?")
fee = input("Enter your fee: ")
print("Would you like to give us a tip?")
answer = input("Yes or no?")
if answer == 'no':
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == 'yes':
tip = input("Would you like to tip 15 percent or 20 percent? ")
if tip == 15:
cost1 = fee / 15 + fee
elif tip == 20:
cost2 = fee / 20 + fee
else:
print("I do not understand.")
else:
print("I do not understand.")
print("Have a wonderful day!")
Also, this way of hard coding options and no easy way to skip questions (once answered 'yes' for example) makes for a very frustrating user experience, but that is another issue.
Edit:
You're also comparing strings to numbers, which will always be false, which saves you from the error, that trying to divide a string by a number would produce
I am currently trying to work on this python school assignment, and I'm lost at how to add a loop to continue ordering, and how to take orders of both coffee and tea. My program only lets you take an order of one, tea or coffee. My except ValueError also causes the order of adding vanilla syrup to the medium and large coffee not unique, and lets it be added to the small coffee as well, when it shouldn't. I am having a lot of trouble with this, and would really appreciate any help or suggestions to as what I could add/try
This is my code:
price = 0
print("Tea is 1, Coffee is 2.")
print("Small is 1, Medium is 2, Large is 3.")
try:
drinkchoice=float(input("What drink would you like?: "))
if(drinkchoice == 1):
TeaAmount=float(input("How many would you like?: "))
else:
CoffeeAmount=float(input("How many would you like?: "))
except ValueError:
print("Error, follow the directions!")
exit()
try:
drinksize=float(input("What size would you like?: "))
if(drinksize == 3 and drinkchoice == 1):
print("1 for yes, 2 for no")
Oprah=float(input("Would you like the Oprah sponsered option for 0.75 more?: "))
if(drinksize == 2 or 3 and drinkchoice == 2):
print("1 for yes, 2 for no")
vanilla=float(input("Would you like a shot of vanilla syurp for 0.50 more?: "))
except ValueError:
print("Error, follow the directions!")
exit()
if(drinkchoice == 1):
if(drinksize == 1):
price=price+2*TeaAmount
if(drinksize == 2):
price=price+3.50*TeaAmount
if(drinksize == 3):
price=price+4.65*TeaAmount
if(Oprah == 1):
teaPrice=round(price,2)
price=price+.75*TeaAmount
OprahPrice=.75*TeaAmount
else:
price=round(price,2)
coffeePrice = 0
vanillaPrice = 0
if(drinkchoice ==2):
if(drinksize == 1):
price=price+2.25*CoffeeAmount
if(drinksize == 2):
price=price+3.75*CoffeeAmount
if(vanilla == 1):
coffeePrice = round(price,2)
price=price+.50*CoffeeAmount
vanillaPrice=.50*CoffeeAmount
else:
price=round(price,2)
vanillaPrice=0
if(drinksize == 3):
price=price+4.85*CoffeeAmount
if(vanilla == 1):
coffeePrice = round(price,2)
price=price+.50*CoffeeAmount
vanillaPrice=.50*CoffeeAmount
else:
price=round(price,2)
vanillaPrice=0
teaPrice = 0
OprahPrice = 0
price = round(price,2)
print("You paid $", teaPrice, "for tea")
print("You paid $", coffeePrice, "for coffee")
print("You paid $", OprahPrice, "for the extra Oprah version")
print("You paid $", vanillaPrice, "for the vanilla syrup")
print("Your bill is $", price)
Here is the assignment
Leaving this as an answer as its too big for a comment.
With the structure of your data you will be much more suited to use a dictionary. This will make your code much easier to read, structure your data better and better support the addition of new drinks and new drink sizes in the future.
Dictionaries store a key and a value which can be called later by dict[key] or dict.get(key).
An example of storing this data could be;
drinks = {'tea': {'small': 1, 'medium': 2, 'large': 3}}
Now when a user specifies what they want, your life and code becomes much easier to manage and understand.
drinks['tea']['small']
#1
However, if tea does not exist, this method of calling your key, value pair would return a KeyError, so it may be better to use get() instead.
drinks.get('tea', {}).get('small')
#1
In the case either key here does not exist, this line will return None which provides a safe method to call your values.
You can also store your drink_options in a dictionary too. When you need to change pricing, just change the value of the key pair in your dict.
For your looping, while True: is a good way to continually loop until a user specifies to stop. It needs to be noted though, if you do not break out of this loop, it would run indefinitely.
You can use break to exit your while loop.
Below you can find some links on some reading which may help you learn more relating to this assignment. Happy learning!
Links
Python Official Documentation - Dictionaries
Python Official Documentation - Break & continue statements
While Loops
Dictionaries in Python
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I'm writing a program as an exercise for if-elif-else statements and I could do with some advice as to why an elif statement is not running.
I want to give the option to pick up rocks for the inventory.
That works, but if I say I do NOT want to pick up the rocks, that elif statement seems to be ignored and I pick up the rocks and they are added to my inventory.
I have no actual errors, but cannot see why the elif statement is not being actined. I have used this several times in the same program as part of this exercise and not had this continual problem.
These are the statements I seem to be having issues with:
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
Here is the whole of the function:
def fog():
global inventory
global rocks_there
print("You walk along the path to the left of the castle when a thick fog starts swirling around you.")
print("Do you want to CARRY on or go BACK to the courtyard?")
choice = input("> ").lower()
if "back" in choice:
grounds()
elif "carry" in choice:
num = random.randint(0,10)
if num < 2:
print("""The fog envelopes you until you have no idea where you are and can see nothing else.
Suddenly you feel yourself fall as you step over the edge of a towering cliff.
You die, but at least you are not undead.""")
exit(0)
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
elif num >= 2 and rocks_there == False:
print("You follow the castle walls around to the front of the castle.")
else:
print("The fog has scrambled your brain and I do not understand you.")
print("I hope you find your way out.")
print("Goodbye!")
exit(0)
If you try this simple code
mylist = []
if "yes" or "y" in mylist:
print("oops")
you'll see that the code is interpreted as
mylist = []
if "yes" or ("y" in mylist):
print("oops")
And since
if "yes":
print("oops")
it will always run through the if-part and never through the elif part. That's because "yes" is considered a truthy value.
What you probably wanted is
if take in ["y", "yes"]:
which is "check if the user input (take) is in the list ([]) of possible answers". And similar for the no-part of the statement.
I'm fairly new to python, so sorry if this is a bit basic.
I have undertaken making a roulette game to improve my programming skills and have come across a very strange error. At first, when I wanted to print the player's balance at the end of the roll and once the results were checked, it printed out the array that holds all the red numbers. I looked over the code that was defining the balance variable but there was nothing that looked like it might affect it.
I for some reason thought that defining balance as int(100) instead of 100 might fix it but i instead got this error:TypeError: checkresults() missing 1 required positional argument: 'bet' I deleted the int in balance and it still persisted. For those wondering, I make checkresults use bet and have even tried moving the place where it goes in the list of variables used but still no fix. balance = checkresults(bet, bet_choice, number, balance, red, black, green, first, second, third) as you can see, it's the first variable it uses. The full code for checkresults is here:
def checkresults(self, bet_choice, number, balance, red, black, green, first, second, third, bet):
if bet_choice == "number":
if bet == number:
balance = balance + (bet_amount*14)
print("You Won!")
else:
print("You Lost")
elif bet_choice == "colour":
if bet == "red":
if number in red:
balance = balance + (bet_amount*2)
print("You Won!")
else:
print("You Lost")
elif bet == "black":
if number in black:
balance = balance + (bet_amount*2)
print("You Won!")
else:
print("You Lost")
else:
if number in green:
balance = balance + (bet_amount*14)
print("You Won!")
else:
print("You Lost")
elif bet_choice == "third":
if bet == "1st":
if number in first:
balance = balance + (bet_amount*3)
print("You Won!")
else:
print("You Lost")
elif bet == "2nd":
if number in second:
balance = balance + (bet_amount*3)
print("You Won!")
else:
print("You Lost")
elif bet == "3rd":
if number in third:
balance = balance + (bet_amount*3)
print("You Won!")
else:
print("You Lost")
return balance
the value for bet is decided by this:
def choosebet():
bet_choice = input("Would you like to bet on a number, colour, or a third? ")
if bet_choice == "number":
bet = int(input("Which number would you like to bet on? "))
elif bet_choice == "colour":
bet = input("Which colour would you like to bet on?")
else:
bet = input("Which third would you like to bet on?")
return bet, bet_choice
I had self in the defining part of the checkresults code, from a previous error. I deleted self and 1: it fixed the new error and 2: the old error didn't come back.
checkresults as defined takes eleven arguments - it looks like the first parameter is supposed to be an instance of the class that checkresults is defined in - when you call the method directly without reference to the instance it thinks you did not pass the eleventh argument.
I am doing the exact same thing. I started python about two and a half months ago, and have been working on a roulette game for the past month.
This doesn't answer the question, but I had similar issues when I started. If your intent is to build out the entire game, the path you are on is not sustainable. There will be too many elif statements and you will want to rip your hair out (as I did).
What I ended up doing was putting all the "constants" in dictionaries. By constants I mean the numbers in each bet (red vs black, odd vs even, etc), the numbers on the wheel, and the payouts for each bet.
From there you can use dictionary methods to lookup up the winning numbers in the bet dictionaries (i.e. is this a red or black number) and then compare that to a dictionary of placed bets, and if there is a match, look up the payout for the bet.
Good luck!
I am creating this game in python and I am trying to get the program to stop running if the user puts in a bet more than they have or if they run out of money. I have used while loops in the past but I can not remember how I did it and other while loop questions; I have tried their solutions but no prevail. If I can get this loop, then I think I can get the second one I will need so the user can keep playing and not have to enter a new starting value sense he/she will be literally playing 1 round only. Anyways, here is my code.
import time
import math
import random
continued='h'
continued2='g'
print("Welcome to gambling 50/50 shot game!!!"
"You will put in an amount to start with and type in"
"the amount you want to bet until your money you started with is gone."
"You will choose either black or red. "
"May the odds be in your favor.")
time.sleep(5)
while continued=='h':
moneyleft=int(input("How much money are you going to start with? $:"))
time.sleep(2)
bet=int(input("How much money are you going to bet this round? $:"))
if bet>moneyleft:
print("sorry, you can't bet more then what you have!")
time.sleep(2)
print("Sorry, I do not play with cheaters!!!")
continued=='z'
time.sleep(2)
colorchosen=int(input("Type 1, for black and 2 for red."))
time.sleep(2)
result=random.randint(1,2)
if result==1:
print("The color was black!!!")
if result==2:
print("The color was red!!!")
time.sleep(3)
if colorchosen==result:
moneyleft=moneyleft+bet
print("Congratulations!!! You won! Your money total is now $", moneyleft)
time.sleep(3)
if not colorchosen==result:
moneyleft=moneyleft-bet
print("Sorry, you lost. Your money total is now $", moneyleft)
time.sleep(3)
if moneyleft<=0:
print("Sorry, your all out of money!!!")
continued=='z'
Fixed a few things up. Notably, I did what commenters already suggested: I moved the initial money_left= input outside of the loop and I used break statements to exit the loop.
import time
import random
print("Welcome to gambling 50/50 shot game!!! "
"You will put in an amount to start with and type in "
"the amount you want to bet until your money you started with is gone. "
"You will choose either black or red. "
"May the odds be in your favor.")
time.sleep(5)
money_left = int(input("How much money are you going to start with? $"))
while True:
time.sleep(2)
bet = int(input("How much money are you going to bet this round? $"))
if bet > money_left:
print("Sorry, you can't bet more then what you have!")
time.sleep(2)
print("Sorry, I do not play with cheaters!!!")
break
time.sleep(2)
color_chosen=int(input("Type 1 for black and 2 for red: "))
time.sleep(2)
result = random.randint(1,2)
if result == 1:
print("The color was black!!!")
if result == 2:
print("The color was red!!!")
time.sleep(3)
if color_chosen == result:
money_left += bet
print("Congratulations!!! You won! Your money total is now ${}.".format(money_left))
time.sleep(3)
else:
money_left -= bet
print("Sorry, you lost. Your money total is now ${}.".format(money_left))
time.sleep(3)
if money_left <= 0:
print("Sorry, your all out of money!!!")
break
You are never changing the value of your variable continued.
When the user attempts to bet more money than they have you execute:
if bet>money:
...
continued=='z'
This will just evaluate to false, not change the state of continued to "z". It seems like what you intended to write was:
continued = 'z'
You did the same thing again later in your code when the user runs out of money:
if moneyleft<=0:
...
continued=='z'
In addition, it would make your code more clear if you change the name of "continued" to "continue" and you used a boolean instead of a character. It's not clear what 'g' and 'z' stand for. If continue is either true or false, its pretty clear that you mean, it's true you should continue the program, or its false, you should not continue the program. Good luck with your game :)