So I am trying to write a code that uses functions to create a menu for user input. It's basically just inputting the amount of dollars you wish and picking which currency to convert it to. I am absolutely lost because every time I attempt to run this code I have so far (Just to make sure I'm on the correct path), I input "1" and say 20 dollars just for example, it tells me that "dollars" is not defined when I clearly have it as a user input.
def DisplayMenu():
print("Choose a menu option:")
print("1. European Euro")
print("2. British Pound")
print("3. Mexican Peso")
print("4. Chinese Yuan")
print("5. Japanese Yen")
print("6. Quit")
selection = int(input("Enter your selection: "))
dollars = eval(input("Enter the dollar amount to convert: "))
def DollarConvert(selection, dollars):
if selection == "1":
conversion = dollars * 0.921
elif selection == "2":
conversion = dollars * 0.807
elif selection == "3":
conversion = dollars * 24.246
elif selection == "4":
conversion = dollars * 7.085
elif selection == "5":
conversion = dollars * 108.03
elif selection == "6":
quit
elif selection > 6:
print("Invalid input.")
DisplayMenu()
print("$ ",dollars," = ",chr(8364),conversion)
Hopefully someone can help me with this because I am out of ideas
You never run or from DollarConvert(), or receive outputs from either function. Change the functions to return values, like this:
def DisplayMenu():
print("Choose a menu option:")
print("1. European Euro")
print("2. British Pound")
print("3. Mexican Peso")
print("4. Chinese Yuan")
print("5. Japanese Yen")
print("6. Quit")
selection = int(input("Enter your selection: "))
dollars = eval(input("Enter the dollar amount to convert: "))
return selection, dollars
def DollarConvert(selection, dollars):
if selection == "1":
return = dollars * 0.921
elif selection == "2":
return = dollars * 0.807
elif selection == "3":
return dollars * 24.246
elif selection == "4":
return dollars * 7.085
elif selection == "5":
return dollars * 108.03
elif selection == "6":
quit
elif selection > 6:
print("Invalid input.")
return None
selection, dollars = DisplayMenu()
conversion = DollarConvert(selection, dollars)
print("$ ",dollars," = ",chr(8364),conversion)
There we go.
In your code, the dollars variable's scope is limited to inside that function. You have to return dollars from the function to make it accessible. Also your dollar convert function is never called, so you need to call it. You also need to add a return statement for the conversion variable. Returning is essential for most all functions, otherwise data is lost.
You could also do it using the global keyword
dollars = None
conversion = None
def DisplayMenu():
global dollars
print("Choose a menu option:")
print("1. European Euro")
print("2. British Pound")
print("3. Mexican Peso")
print("4. Chinese Yuan")
print("5. Japanese Yen")
print("6. Quit")
selection = input("Enter your selection: ")
dollars = int(input("Enter the dollar amount to convert: "))
DollarConvert(selection, dollars)
def DollarConvert(selection, dollars):
global conversion
if selection == "1":
conversion = dollars * 0.921
elif selection == "2":
conversion = dollars * 0.807
elif selection == "3":
conversion = dollars * 24.246
elif selection == "4":
conversion = dollars * 7.085
elif selection == "5":
conversion = dollars * 108.03
elif selection == "6":
quit
elif selection > 6:
print("Invalid input.")
DisplayMenu()
print("$ ",dollars," = ",chr(8364),conversion)
Also, one more mistake on line 12 & 13, i.e
selection = int(input("Enter your selection: "))
changed to
selection = input("Enter your selection: ")
and
dollars = eval(input("Enter the dollar amount to convert: "))
changed to
dollars = int(input("Enter the dollar amount to convert: "))
Related
So I am making a restaurant menu in Python, I got everything to work besides the program keeping track of the total cost. I've tried a few different things but no luck so far. It's probably something super simple but I can't figure it out. P.S. I'm a Python beginner so I'm still trying to get used to and learn this language lmao.
print("1. Cheeseburger: $3.50")
print("2. Gyro: $6.00")
print("3. Chicken Sandwich: $2.50")
print("4. Burrito: $7.00")
print("5. Fries: $1.50")
print("6. Exit")
while True:
choice = input("Enter a choice from 1-6\n")
totalPrice = 0
if choice == "1":
price = 3.00
totalPrice += price
elif choice == "2":
price = 6.00
totalPrice += price
elif choice == "3":
price = 2.50
totalPrice += price
elif choice == "4":
price = 7.00
totalPrice += price
elif choice == "5":
price = 1.50
totalPrice += price
elif choice == "6":
print("Exiting...")
print(totalPrice)
break
else:
print("Enter a valid choice!")
Only a litle mistake: the variable totalPrice must be initialized outside of the loop.
See the code below:
print("1. Cheeseburger: $3.50")
print("2. Gyro: $6.00")
print("3. Chicken Sandwich: $2.50")
print("4. Burrito: $7.00")
print("5. Fries: $1.50")
print("6. Exit")
totalPrice = 0 # <--- here is the right position for init totalPrice
while True:
choice = input("Enter a choice from 1-6\n")
if choice == "1":
price = 3.00
totalPrice += price
elif choice == "2":
price = 6.00
totalPrice += price
elif choice == "3":
price = 2.50
totalPrice += price
elif choice == "4":
price = 7.00
totalPrice += price
elif choice == "5":
price = 1.50
totalPrice += price
elif choice == "6":
print("Exiting...")
print(totalPrice)
break
else:
print("Enter a valid choice!")
I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")
I'm trying to write a simple program, but I meet a problem that the program does not output the given variable "tax" in the end.
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
tax = total*0.06
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
when you initialized tax, you gave it a value of 0 because total*0.06 at that point equaled zero.
python goes line by line so the variable "tax" didn't change its value for the whole code, you only changed "total".
so to get the tax, you should calculate it again.
print("Current total: $",total)
tax=0.06*total
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
Here the value of total gets updated but the tax is calculated before the check as given below, hence tax will output tax = total*0.06 where initially total=0
Please try this:
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = tax = 0
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
tax = total*0.06
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
I guess your problem is solved.Also start using python dictionary instead of using lots of if else statements
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
tax = total*0.06
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
price_dict = {
1: menu1,
2: menu2,
3: menu3,
4: menu4
}
if 0 < choose < 5:
total += price_dict[choose]
else:
if choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
tax = total*0.06
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
Now your tax is always 0. You have to calculate the tax at the end. Like this:
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $", total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
print("Current total: $", total)
tax = total * 0.06
print("Sales tax: $", tax)
print("Total Bill: $", total + tax)
print("Have a nice day!")
main()
I'm needing help on getting the loop in my function Deductions to work.
I've tried looking through similar problems on stackoverflow but struggling to get my head around them.
def Deductions(money, Tax, TotalInsurance):
deductions = 0
global TotalDed
TotalDed = 0
choice = ""
while not choice == "Y" or choice == "N":
try:
choice = str(input("Do you want to add any more deductions to your income, e.g car, rent or mortgage? Y/N : "))
except ValueError:
print("Must enter Y or N")
if choice == "Y":
while choice == "Y":
AddDed = int(input("How much would you like to deduct: "))
deductions = AddDed + deductions
loop = str(input("Would you like to add more deductions? Y/N: "))
if loop == "Y":
choice == "Y"
elif loop == "N":
choice =="N"
elif choice == "N":
TotalDed = TotalTax + deductions
print("Income: £", money)
print("Taxed: £", Tax)
print("National Insurance: £", TotalInsurance)
print("Other Deductions: £", deductions)
print("Total Deductions: £", TotalDed)
return TotalDed
I'm wanting to make sure that my loop only accepts "Y" and "N". then to proceed to ask for Deductions.
I think there are several mistakes in your code :
As pointed out in the comments, from what I understand that you're trying to do, you should use while not (choice == "Y" or choice == "N").
You seem to have forgotten TotalTax = Tax + TotalInsurance.
try/except will not throw out a ValueErrorfrom input, so what you're looking for is probably an else clause after if and elif.
choice == "Y" is a boolean, it does not set a value. You're looking for choice = "Y".
I think you're confused when you're using the choice variable in a second while loop and then use loop to set a value to choice. Below is another structure I would choose for what you're trying to do.
You can also add more protection against the possible wrong values from input statements.
To sum this up, here is what I think you should write :
def Deductions(money, Tax, TotalInsurance):
deductions = 0
global TotalDed
TotalDed = 0
TotalTax = Tax + TotalInsurance
choice = ""
while choice != "N":
choice = input("Do you want to add any more deductions to your income, e.g car, rent or mortgage? Y/N : ")
if choice == "Y":
AddDed = float(input("How much would you like to deduct: "))
deductions = AddDed + deductions
elif choice != "N":
print("Must enter Y or N")
TotalDed = TotalTax + deductions
print("Income: £", money)
print("Taxed: £", Tax)
print("National Insurance: £", TotalInsurance)
print("Other Deductions: £", deductions)
print("Total Deductions: £", TotalDed)
return TotalDed
Also
AddDed = float(input("How much would you like to deduct: "))
deductions = AddDed + deductions
can be replaced with
valid_added_value = False
while not valid_added_value:
try:
AddDed = float(input("How much would you like to deduct: "))
valid_added_value = True
except ValueError:
print('Must be a numerical value')
deductions = AddDed + deductions
for extra protection, because it could throw a ValueError.
Also you don't need str in front of input because input already returns a str object in python3.
I'm not sure either why you need global TotalDed since you already return it but maybe you have a good reason.
Okay so I have done most of the work but my pin code isn't working properly. You can enter a code but I want it to be you can only enter e.g 1234 to get in as so far you can but any number and get it, I tried using an else statement but I cant get it to work, any help? Also does anyone know how I could write this stuff to a file, for example, your write your name e.g joe, it finds your balance etc maybe I could do this with the pin too? not sure need some help, thanks
balance = float(0)
userInput = None
pin = int(input('Please enter the 4 digit pin on your card:'))
if pin == (1234):
print('Correct pin!')
print "Hello, welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"