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
Related
This is Python in Visual Studio Code. I'm making a program for school that essentially is an robotic restaurant waitress. I have to do it the way the assignment outline says which is why it might be a little weird. Then I have to personalize it and make it creative. It asks how much the price of an adult meal and a child meal. Then it asks how many children and adults there are. Then it asks what the sales tax rate is. The assignment only needs me to be able to calculate all that and get the subtotal and total and then give change. I've already done that and I'm making it fancy. I made a loop that asks if they have a lucky draw coupon that generates a random monetary value between $1.00-$5.00. Then If they say yes it will bring them to the first part of the loop that gives them the total with the coupon and then asks for payment. If they say no, then it just asks them for the payment.
I want to go the extra mile and put a loop in a loop, which I think is called a nested loop (This is my first week of Python.) I want it to recognize if the amount they pay is less then the total, then ask for the user to try again until they put an amount more than the total. Pretty much I just want it to know that the payment isn't enough.
My problem is I've never used nested loops and this is the first time I've even used a loop period. I also don't know how to make a loop based on a variable that's not constant because it's based on what the user inputs when prompted. I could do it if I could put the parameters in a fixed range, but the range will always be different based on what they enter in the beginning.
How do I make a nested loop recognize a variable that is never the same?
How do I make it recognize the payment is not enough to cover the total?
This is the loop I have. And I want to put two nested loops in the loop. One for if and one for elif so that it works for both "options".
Here is my snippet:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
payment = float(input("Please enter your payment amount: "))
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
Any suggestions? I've searched all over Stackoverflow and google and cannot find anything specific to my situation.
Your approach is good for implementing this. Looping while asking for payment and validating that it is correct before allowing the loop to break will do the job. For your first if block, this is how that would look:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
#Ask for the payment inside of the new loop
while True:
payment = float(input("Please enter your payment amount: "))
if payment - total + coupon > 0:
print("That's not enough money to pay your bill. Try again")
else:
break
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
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 :)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I have just started to use python. The first program I made was a tip calculator and I have made three versions to rewrite and to add more. The next part of code I want to write is a loop that prompts a yes or no question. When 'yes' I want the program to loop back to the very start, when 'no' I want the program to exit, and when there is an invalid command I want the program to print('Invalid command.') and continue to wait for a 'yes' or 'no'. Here is the code:
print('Good evening sir, I am Tippos! Please, tell me the price of your meal and how much you would like to tip and I\'ll do the math for you!')
bill_amt = input('First sir, what was the price of your meal?(Please do not use signs such as "$"):')
tax = 1.13
x = float(bill_amt)
tip_amt = input('And how much would you like to tip? 10, 15, or maybe 20% Go on, any number sir!(Please do not use signs such as "%"):')
y = float(tip_amt)
tip_amt = x * (y / 100)
print('Your tip will cost you an extra' ,tip_amt, 'dollars.')
total_amt = (x + y) * tax
print('Your total cost will be' ,total_amt, 'dollars, sir.')
How do I add a loop that will restart the program at a certain input?
Thanks!
-Pottsy
a good way is one such as the following:
done = False
while not done:
print('Good evening sir, I am Tippos! Please, tell me the price of your meal and how much you would like to tip and I\'ll do the math for you!')
bill_amt = input('First sir, what was the price of your meal?(Please do not use signs such as "$"):')
tax = 1.13
x = float(bill_amt)
tip_amt = input('And how much would you like to tip? 10, 15, or maybe 20% Go on, any number sir!(Please do not use signs such as "%"):')
y = float(tip_amt)
tip_amt = x * (y / 100)
print('Your tip will cost you an extra' ,tip_amt, 'dollars.')
total_amt = (x + y) * tax
print('Your total cost will be' ,total_amt, 'dollars, sir.')
if 'yes' != input('Do you want to start over?').lower():
done = True
where a variable done is set up in a while loop, then when you ask the question to start over, if the answer is not exactly yes (in any case), then you stop your algorithm.
Im a very new Python user (2.7) and have been working my way through the Learn Python The Hard Way course and up to chap 37 and decided to do read through some other learning materials and go over the basics again and do exercises there. I have been reading through this:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html
and I just did this:
3.1.4.1. Graduate Exercise
Write a program, graduate.py, that prompts students for how many credits they have. Print whether of not they have enough credits for graduation. (At Loyola University Chicago 120 credits are needed for graduation.)
and this is my code for that:
print "How many credits do you currently have: "
credits = raw_input("> ")
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
but no mater what number I input it just gives "Sorry not enough credits" as the answer every time, why? I have tried moving some things around and making it > instead of >= but nothing worked. Im sure this is something stupidly simple Im missing but I cant figure it out.
I've done several other if statement exercises in the LPTHW course similar to this and never had a problem.
raw_input() returns a string:
>>> credits = raw_input("> ")
> 150
>>> type(credits)
<type 'str'>
You need to cast it to int:
credits = int(raw_input("> "))
In your code, at the if statement you are comparing a str type with a int type. so it is not working as you axpected. Cast the credit as int
print "How many credits do you currently have: "
credits = raw_input("> ")
credits = int(credits)
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
I am refering to the same material by Dr. Andrew Harrington and I am doing the same program, my program may look pretty much amatuerish so I would highly appreciate if someone can kindly refine it
def graduateEligibility(credits):
if credits >= 120:
print("Congratulations on successfully completing the course.....see you on graduation day!")
else:
print("Sorry! Your credits are below 120, please kindly retake the evaluaton tests")
def main():
E = float(input("Enter your English marks:"))
M = float(input("Enter your Mathematics marks:"))
P = float(input("Enter your Physics marks:"))
C = float(input("Enter your Chem marks:"))
Cf = float(input("Enter your Comp.Fundamentals marks:"))
Fin_Edu = float(input("Enter your finance marks:"))
Const = float(input("Enter your Constitutional.Stds marks:"))
R = float(input("Enter your Reasoning marks:"))
TotalCredits = (E+M+P+C+Cf+Fin_Edu+Const+R)
YourCredits = graduateEligibility(TotalCredits)
main()
For simplicity sakes i have taken 8 subjects each have 20 credits.
You need to accept integer input for that and also need to handle non integer inputs.
print "How many credits do you currently have: "
try:
credits = int(raw_input("> "))
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
except ValueError:
print "Invalid input"
Output:
> 100
Sorry not enough credits
> 121
You have graduated!
> aaaa
Invalid input