Python Not Using Elif Statement - python

I'm trying to make a virtual coffee shop, in which the amount of an item a customer asks for would adjust the total for payment. However, when I run my code, and I enter more than 1 of an item, it simply skips the step that would inform the user of their total.
Code:
import time
print("Hello! Welcome to George's Coffee.")
name = input("What is your name for the order?\n")
print("\nHello " + name + "! Thank you for coming to George's Coffee!\n")
print("On todays menu, we have the following:\n" + "Lattee\n" + "Hot Chocolate\n" + "Mocha\n" + "Celcius\n" + "Cappuchino\n" + "Black Coffee\n" + "All items are $8 because we need money to fund the hacking of the government.")
price = 8
order = input("\nWhat would you like to order today?\n")
quantity = input("How many " + order + "s would you like?\n")
#singular (=1)
if quantity == "1":
if order == "Lattee":
latte_total = float(2.95) * int(quantity)
print("Amazing choice! That will be $" + str(latte_total) + ". Please enter your credit card.")
elif order == "Hot Chocolate":
hot_chocolate_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(hot_chocolate_total) + ". Please enter your credit card.")
elif order == "Mocha":
mocha_total = 5 * int(quantity)
print("Amazing choice! That will be $" + str(mocha_total) + ". Please enter your credit card.")
elif order == "Celcius":
cel_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(cel_total) + ". Please enter your credit card.")
elif order == "Cappuchino":
capp_total = 6 * int(quantity)
print("Amazing choice! That will be $" + str(capp_total) + ". Please enter your credit card.")
elif order == "Black Coffee":
coffee_total = 3 * int(quantity)
print("Amazing choice! That will be $" + str(coffee_total) + ". Please enter your credit card.")
else:
total = price * int(quantity)
print("Amazing choice! That will be $" + str(total) + ". Please enter your credit card.")
time.sleep(3)
print("\nYour " + quantity + " " + order + " will be ready soon! Please have a seat, and we will call your name when it's ready.\n")
time.sleep(10)
print(name + "! Your " + order + " is ready! Please come collect it.\n")
time.sleep(2)
print("Enjoy your beverage, " + name + ("!"))
Output: terminal output
This is my first time posting, so it made it a link
Output when I only do 1: terminal output with only 1
Let me know how I can solve this. Thanks for your help in advance.

In your code you are using
if quantity == "1":
do all the price calculations
That's why it is only working when you get just 1 item, quantity is equal to "1". When you use another quantity the if statement just ignores the rest of the code.
To solve this issue you can delete that line.
import time
print("Hello! Welcome to George's Coffee.")
name = input("What is your name for the order?\n")
print("\nHello " + name + "! Thank you for coming to George's Coffee!\n")
print("On todays menu, we have the following:\n" + "Lattee\n" + "Hot Chocolate\n" + "Mocha\n" + "Celcius\n" + "Cappuchino\n" + "Black Coffee\n" + "All items are $8 because we need money to fund the hacking of the government.")
price = 8
order = input("\nWhat would you like to order today?\n")
quantity = input("How many " + order + "s would you like?\n")
#singular (=1)
if order == "Lattee":
latte_total = float(2.95) * int(quantity)
print("Amazing choice! That will be $" + str(latte_total) + ". Please enter your credit card.")
elif order == "Hot Chocolate":
hot_chocolate_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(hot_chocolate_total) + ". Please enter your credit card.")
elif order == "Mocha":
mocha_total = 5 * int(quantity)
print("Amazing choice! That will be $" + str(mocha_total) + ". Please enter your credit card.")
elif order == "Celcius":
cel_total = 2 * int(quantity)
print("Amazing choice! That will be $" + str(cel_total) + ". Please enter your credit card.")
elif order == "Cappuchino":
capp_total = 6 * int(quantity)
print("Amazing choice! That will be $" + str(capp_total) + ". Please enter your credit card.")
elif order == "Black Coffee":
coffee_total = 3 * int(quantity)
print("Amazing choice! That will be $" + str(coffee_total) + ". Please enter your credit card.")
else:
total = price * int(quantity)
print("Amazing choice! That will be $" + str(total) + ". Please enter your credit card.")
time.sleep(3)
print("\nYour " + quantity + " " + order + " will be ready soon! Please have a seat, and we will call your name when it's ready.\n")
time.sleep(10)
print(name + "! Your " + order + " is ready! Please come collect it.\n")
time.sleep(2)
print("Enjoy your beverage, " + name + ("!"))

Related

I'm getting the wrong output in my if statment

I'm new to python and am trying to fix this and By defualt its running the else statment I don't understand and need help. I'm new so please dumb your answers down to my -5 iq
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
if "" > menu:
order = input("What Would you like? \n ")
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
else:
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
I changed the if "" to on_menu and list the options but it didn't work, and I asked people on discord.
menu = ["Baguette" , "Crossiant" , "Coffee" , "Tea" , "Cappuccino "]
count = 0
for item in menu:
print(str(count) +" -> "+str(item))
count += 1
order = int(input("\n What Would you like? \n "))
if order > len(menu) or order < 0 or order == "" or not menu[order]:
print("Sorry Thats not on the menu")
quit()
orderCount = int(input("How many " + menu[order] + " would you like?"))
print("Your " + str(orderCount) + " " + menu[order] + " will be ready soon!\n\n\n")
amount = int(4) * int(orderCount)
print("Thank you, your total is: $" + str(amount))
print("Your " + str(amount) + " of " + str(menu[order]) + " is ready!")
print("Please enjoy you " + str(menu[order]) + "!")
print("Please come again!")
Currently you are not checking the user input, you are just checking for a False statement based on what you defined. You need to check if the user input is on the menu, else quit the program.
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
name = input("What your name? \n ")
order = input("What Would you like? \n ")
if not order.lower() in menu.lower(): # checking if user input is in the menu
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#input name
name = input("What is your name?\n")
#create menu
menu = "Baguette, Crossiant, Coffee, Tea and Cappuccino"
#display menu
print(menu)
#input order
order = input("What would you like?\n")
#if the order item is in the menu
if order in menu:
#input quantity
amount = input("How many " + order + "s would you like? ")
#display message
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
#setting price of all items to 4
price = 4
#calculating total
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#if the item is not in menu
else:
#display message
print("Sorry Thats not on the menu")
Hope this helps! I have added the explanation as comments.

Want to select a random item from a list and reuse the item in a different function

my code is pretty messy as I am new but I cant figure this out!
I have only included the relevant pieces of my code btw.
Pretty much What i want it to do is say the same location twice for random_place1 and then a new location for random_place2. Currently it just gives me three separate locations, because i am just calling for random_place1 to rerandomize.
def random_place1():
import random
locations = ["Paris" , "New York", "San Francisco" , "Tokyo", "Istanbul", "São Paulo", "Xi'an", "Bogotá", "Casablanca", "Rabat"]
first_place = random.choice(locations)
return (first_place)
def random_place2():
import random
locations = ["London" , "Miami" , "Chicago", "Cairo", "Vienna" , "Manila", "Munich", "Delhi"]
second_place = random.choice(locations)
return(second_place)
def main():
answer = input("Type Yes to continue or No to exit: ")
if answer == "yes":
print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
restart2()
elif answer == "y" :
print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
restart2()
elif answer == "Yes":
print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
restart2()
elif answer == "YES":
print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
restart2()
elif answer == "Y":
print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
restart2()
elif answer == "no":
print("\nThanks for trying out the Madlibs Generator!")
elif answer == "n":
print("\nThanks for trying out the Madlibs Generator!")
elif answer == "No":
print("\nThanks for trying out the Madlibs Generator!")
elif answer == "NO":
print("\nThanks for trying out the Madlibs Generator!")
elif answer == "N":
print("\nThanks for trying out the Madlibs Generator!")
else:
print("\nInvalid response please try again!")
restart()
You can call the random place methods and store the value it returns in a variable to use that value later. One coding principle you might want to look at is called "DRY" (Dont repeat yourself). If you see your self writing a lot of the same code then chances are you can take a better approach.
So below is just a quick update of your code to make it cleaner. You could really not bother with the func random_place as instead of calling it from main we could just call random.choice. However i have included it to show you that you dont need to write random_place twice. you could write it once and give it a locations to chose from.
Also you can take the input and make it lower case. then you only need to test for things like "yes" or "y" you dont need to test for all the case sensitive version. Thus you only write the print line once.
import random
locations1 = ["Paris", "New York", "San Francisco", "Tokyo", "Istanbul", "São Paulo", "Xi'an", "Bogotá", "Casablanca",
"Rabat"]
locations2 = ["London", "Miami", "Chicago", "Cairo", "Vienna", "Manila", "Munich", "Delhi"]
def random_place(locations):
return random.choice(locations)
def main():
while True:
answer = input("Type Yes to continue or No to exit: ").lower()
if answer == "yes" or answer == "y":
location1 = random_place(locations1)
location2 = random_place(locations2)
print(f"Last year i went to {location1}. This year i was going to go again to {location1}.",
f"However my friends suggested to go to {location2} as the people in {location2} are nicer")
elif answer == "no" or answer == "n":
print("\nThanks for trying out the Madlibs Generator!")
break
else:
print("\nThats not a valid input")
main()
OUTPUT
Type Yes to continue or No to exit: yes
Last year i went to São Paulo. This year i was going to go again to São Paulo. However my friends suggested to go to Manila as the people in Manila are nicer
Type Yes to continue or No to exit: nodf
Thats not a valid input
Type Yes to continue or No to exit: no
Thanks for trying out the Madlibs Generator!

Why does my code not allow me to loop a certain section of code, instead looping the entire code?

So I am currently creating a small stock broker game using python for an assignment I have, and I have hit a problem. My next lesson isn't until Tuesday next week, and I can't seem to find any good solutions to my issue. Basically, this code is intended to initially decrease the time by 1 every time the player decides to wait a day, however the time remains at 20 no matter how many times the player waits. I am also unsure of how to make it so that my code loops the user input section: "Did you want to buy stocks, sell stocks or wait a day?" Until the user says he would like to wait. Is there a fix for this issue, and if so, what is it?Here is the code I am talking about:
stocks = 0
time = 21
money = 100
print("You have $" + str(money) + " in your bank.")
while time > 0:
stock = random.randint(1,20)
time = time - 1
while True:
print("You have " + str(time) + " days remaining until the market closes")
print("Stocks are currently worth: $" + str(stock))
choice = input("Did you want to buy stocks, sell stocks or wait a day? ")
if choice.casefold() == "buy":
while True:
numberBuy = int(input("Enter the number of stocks that you would like to buy: "))
if numberBuy * stock > money:
print("You don't have the money for that")
else:
break
money = money - (numberBuy * stock)
stocks = stocks + numberBuy
print("You bought " + str(numberBuy) + " stocks and you spent $" + str(numberBuy * stock) + " buying them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
elif choice.casefold() == "sell":
while True:
numberSell = int(input("Enter the number of stocks that you would like to sell: "))
if numberSell > stocks:
print("You don't have enough stocks for that. You have " + str(stocks) + " stocks and you want to sell " + str(numberSell))
else:
break
stocks = stocks - numberSell
money = money + (numberSell * stock)
print("You sold " + str(numberSell) + " stocks and you made $" + str(numberSell * stock) + " selling them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
elif choice.casefold() == "wait" or "wait a day" or "wait day":
print("You wait for the next day to come. At the end of the day, you have $" + str(money) + " in your bank account and you have " + str(stocks) + " stocks to")
print("your name")
print(" ")
print("===========================================================================================================")
print(" ")```
The reason time never changes is because all of the code based on user input choices is in a second while loop, which currently has no form of exit. A quick fix is to move the line time = time - 1 to the appropriate option in the if statement. Also I think you should remove the second while loop entirely, because the stock price will never change.
while time > 0:
stock = random.randint(1,20)
print("You have " + str(time) + " days remaining until the market closes")
print("Stocks are currently worth: $" + str(stock))
choice = input("Did you want to buy stocks, sell stocks or wait a day? ")
if choice.casefold() == "buy":
while True:
numberBuy = int(input("Enter the number of stocks that you would like to buy: "))
if numberBuy * stock > money:
print("You don't have the money for that")
else:
break
money = money - (numberBuy * stock)
stocks = stocks + numberBuy
print("You bought " + str(numberBuy) + " stocks and you spent $" + str(numberBuy * stock) + " buying them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
elif choice.casefold() == "sell":
while True:
numberSell = int(input("Enter the number of stocks that you would like to sell: "))
if numberSell > stocks:
print("You don't have enough stocks for that. You have " + str(stocks) + " stocks and you want to sell " + str(numberSell))
else:
break
stocks = stocks - numberSell
money = money + (numberSell * stock)
print("You sold " + str(numberSell) + " stocks and you made $" + str(numberSell * stock) + " selling them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
elif choice.casefold() == "wait" or "wait a day" or "wait day":
time = time - 1
print("You wait for the next day to come. At the end of the day, you have $" + str(money) + " in your bank account and you have " + str(stocks) + " stocks to")
print("your name")
print(" ")
print("===========================================================================================================")
print(" ")

Avoiding using / overwriting global variables (with simple example)

TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
requestedTickets = ticketsWanted(userName)
def calculateCost():
ticketQuantity = requestedTickets
totalCost = ticketQuantity * TICKETPRICE
return totalCost
costOfTickets = calculateCost()
def confirm():
global requestedTickets
global costOfTickets
tickets = requestedTickets
totalCost = calculateCost()
print("Okay so that will be " + str(tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/N) : ")
while confirmationResponse == "n":
requestedTickets = ticketsWanted(userName)
costOfTickets = calculateCost()
print("Okay so that will be " + str(requestedTickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/N) : ")
confirm()
def finalStage():
print("Your order is being processed.")
finalStage()
This is a simple program that:
Asks a user how many tickets they want
Calculates the cost of the tickets
Then asks if it's okay to go ahead with the purchase
How could I change the way I'm doing things to not have to overwrite the requestedTickets and costOfTickets global variables?
(they're being overwritten in the confirm function, if a user replies with an "n" declining the confirmation of purchase.)
I'm trying to learn best practices.
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
def calculateCost(n_tickets):
totalCost = n_tickets * TICKETPRICE
return totalCost
def confirm(userName):
n_tickets = ticketsWanted(userName)
totalCost = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/n) : ")
while confirmationResponse == "n":
n_tickets = ticketsWanted(userName)
costOfTickets = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/n) : ")
def finalStage():
print("Your order is being processed.")
confirm(userName)
finalStage()

Transaction Record of an ATM Program in Python

My assignment is to keep a record of the transactions of an ATM program in a text file. After every deposit or withdraw you must update the file with the transaction type, amount deposited/withdrawn, and updated balance. I am able to get the text file to print out the current balance but only for one deposit/withdraw. Additionally, when the program runs it is supposed to open the file with the transactions and find the current balance for the account, but each time I run the program the new text just replaces the old.
Here is my code:
balancefile=open("balancefile.txt", "w")
balancefile.write("Starting balance is $10000 \n")
USER_BALANCE=10000
name=input("What is your name? ")
print(name +"," + " " + "Your current balance is: $" + str(USER_BALANCE))
while True:
answer=input("Would you like to deposit, withdraw, check balance, or exit? ")
if answer=="deposit" or answer== "Deposit":
x= input("How much would you like to deposit? ")
USER_BALANCE += float(x)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You have deposited an amount of $" + x + "." + " " + "Current balance is $" + str(USER_BALANCE) +"\n")
continue
elif answer== "withdraw" or answer== "Withdraw":
y= input("How much would you like to withdraw? ")
if float (y)<=USER_BALANCE:
USER_BALANCE -= float(y)
print (name + "," + " " + "Your new balance is: $" + str(USER_BALANCE))
balancefile.write("You withdrew an amount of $" + y + "." + " " + "Current balance is $" + str(USER_BALANCE) + "\n")
continue
else:
print ("Cannot be done. You have insufficient funds.")
elif answer== "check balance" or answer== "Check Balance":
print ("$" + str(USER_BALANCE))
elif answer== "exit" or answer== "Exit":
print ("Goodbye!")
balancefile.close()
break
else:
print ("I'm sorry, that is not an option")
Please help! To clarify, the original amount in the account is $10,000 but you are supposed to be able to re-enter the program after exiting using the last updated balance in the text file.
As the commenters have noted, the file mode 'w' will truncate the file proir to write, and 'a' will open a file for appending. This is described in further detail in the Python documentation.

Categories

Resources