I'm getting the wrong output in my if statment - python

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.

Related

Python Not Using Elif Statement

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 + ("!"))

How to ignore certain strings from user input?

Beginner question:
How do I have my input code ignore certain strings of text?
What is your name human? I'm Fred
How old are you I'm Fred?
How do I ignore user input of the word "I'm"?
How old are you I'm Fred? I'm 25
Ahh, Fred, I'm 25 isn't that old.
How do I again ignore user input when dealing with integers instead?
This is the code I have so far:
name = input("What is your name human? ")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
You could use .replace('replace what','replace with') in order to acheive that.
In this scenario, you can use something like:
name = input("What is your name human? ").replace("I'm ","").title()
while True:
try:
age = int(input("How old are you " + name + "? ").replace("I'm ",""))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
Similarly, you can use for the words you think the user might probably enter, this is one way of doing it.
Why not use the list of words that should be ignored or removed from the input, i suggest you the following solution.
toIgnore = ["I'm ", "my name is ", "i am ", "you can call me "]
name = input("What is your name human? ")
for word in toIgnore:
name = name.replace(word, "")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
The output is following

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