When I attempt to call the menu function in each choice after the conversion is run, it will take me back to the menu but will only convert in the original selection. If I choose option 1 first after the convertCelsius function is ran and it takes me back to the menu function, any choice will still only convert to celsius. How do I get call the menu function so I can run each choice again.
def menu():
print("1. Celsius to Fahrenheit")
print('2. Fahrenheit to Celsius')
print('3. Exit')
pick = int(input('Enter a choice: '))
return pick
def convertCelsius():
temperature = float(input('Write temp to convert from Celsius to Fahrenheit: '))
fahrenheitTemperature = ((temperature * 1.8) + 32)
print('Fahrenheit temperature is: ',fahrenheitTemperature)
def convertFahrenheit():
temperature = float(input('Write tempt to convert from Fahrenheit to Celsius: '))
celsiusTemperature = ((temperature - 32)* 5/9)
print("Celsius temperature is: ", celsiusTemperature)
def main():
choice = menu()
while choice != 3:
if choice == 1:
convertCelsius()
menu()
elif choice == 2:
convertFahrenheit()
menu()
elif choice==3:
choice = menu()
main()
I think you meant to do choice = menu() every time:
def main():
choice = menu()
while choice != 3:
if choice == 1:
convertCelsius()
elif choice == 2:
convertFahrenheit()
choice = menu()
Related
I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
def main_menu(subtotal):
while True:
print("1) Appetizers")
print("2) Option 2")
print("3) Option 3")
print("4) Option 4")
print("5) Option 5")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 5 or choice < 1:
print("Please choose an option from 1 to 5")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 1:
appetizers(subtotal)
"""
elif choice == 2:
option_2(subtotal)
elif choice == 3:
option_3(subtotal)
elif choice == 4:
option_4(subtotal)
elif choice == 5:
end(subtotal)
return subtotal
"""
def appetizers(subtotal):
while True:
print("1) Option 1")
print("2) Option 2")
print("3) Option 3")
print("4) Return to Main Menu")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
product_amount = 1
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 4 or choice < 1:
print("Please choose an option from 1 to 4")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 4:
return subtotal
else:
while True:
try:
product_amount = int(input("How many would you like? "))
break
except ValueError:
print("Please enter whole numbers only.")
while product_amount > 100000 or product_amount < 1:
print("Please choose an option from 1 to 100,000")
product_amount = int(input("How many would you like? "))
if choice == 1:
subtotal = subtotal + (product_amount * 4.99)
elif choice == 2:
subtotal = subtotal + (product_amount * 2.99)
elif choice == 3:
subtotal = subtotal + (product_amount * 8.99)
For this project's sake, I don't want to use global variables. I only want to use the subtotal variable as a parameter throughout the program and continuously alter its value throughout the program and make calculations with it. I want to do this by passing it through other functions.
Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:
# ...
if choice == 1:
subtotal = appetizers(subtotal)
i have assignment and we need to convert celsius to fahrenheit and vice versa. i have to loop the program but i dont know how.
my code is working but its still wrong.
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
if repeat == "yes":
main()
else:
exit()
main()
Hi that's because variable has scope in which you can read their modifications, repeat modification in main() are not visible outside of their scope: here the main function.
Variables thatcan be "inspect" everywhere are called globals, and you should declare them at the beggining of a file outside of a function.
You have many solution to your problem, if you want to stay close from your actual code, here is one:
from sys import exit
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
return input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
repeat = main()
if repeat.lower() == 'no':
exit()
The problem with your code is that you ran main() after finishing in your last line of code
This will work great for you:
def main():
for _ in range(10):
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return ((9 / 5) * C) + 32
temp = float(input("Enter Temp: "))
print(temp, "Celsius is", c_to_f(temp), "Fahrenheit")
if choice == "b":
def f_to_c(F):
return (5 / 9) * (F - 32)
temp = float(input("Enter Temp: "))
print(temp, "Fahrenheit is", f_to_c(temp), "Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
if repeat == "yes":
main()
else:
exit()
if __name__ == '__main__':
main()
The problem with your code is your last user input.
This will work great for you:
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = str(input("Do you want to convert again? (Yes/No): "))
for _ in range(10):
if repeat == "yes" or repeat == "Yes":
main()
else:
exit()
if __name__ == '__main__':
main()
Have Fun with CODE :)
This code should work
choice = 'y';
while choice != 'e':
choice = input('If you want to convert c to f press a\nIf you want to convert f to c press b\nIf you want to exit press e');
if choice == 'a':
c = int(input('Enter temp in C'));
print("F =", c*1.8+32);
elif choice == 'b':
f = int(input('Enter temp in F'));
print("C =", (F-32)/1.8);
I've been attempting to code this program for the past half a month or so but I'm stumped and I need to make substantial progress soon to meet my deadline, any help/advice would be appreciated. Apologies for the bad formatting, thanks for any help you can provide.
def main():
choice = printMenu()
print(choice)
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4]: Exit")
def choice = int(input("Enter your choice: "))
while choice !=0:
elif choice== 1:
print("$52,324")
elif choice== 2:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice== 3:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
if sum <= "52,324"
print("You're eligible for NRAS!")
else
print ("Sadly, you're not eligible.")
elif choice== 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
I have corrected most of the mistakes and the code works fine. I have also added comments to highlight the changes I made.
But there a lot of questionable things that were going on in this code. I suggest you to look into python syntax properly.
def add_num(a,b):
sum = a+b
return sum
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4] Exit")
ch = int(input('Enter your choice : ')) # added a variable to read the choice.
return ch # then return this choice when this function is called.
def choice(choice):
while choice != 0:
if choice== 1: # changed the elif to if.
print("$52,324")
break # added a break due to infinite loop
elif choice == 2:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice == 3:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
SUM = add_num(num1, num2) # calling the add_num function here.
if SUM <= 52324: # changed this to int type instead of a string.
print("You're eligible for NRAS!")
else:
print ("Sadly, you're not eligible.")
elif choice == 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
def main():
ch = menu()
choice(ch)
if __name__ == "__main__": # this is how you call a main() in python.
main()
I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...
How can I use the choice variable in my menu() function to return the choice to my while loop?
def menu():
print("MENU")
print("1) Test")
print("2) Quit")
choice = int(input("\nChoose an option : "))
return choice
while choice != 2 :
menu()
if choice == 1 :
do_this
elif choice == 2 :
print("This program will terminate.")
break
else :
print("Invalid option... ")
you can simply do it like this
def menu():
print("MENU")
print("1) Test")
print("2) Quit")
choice = int(input("\nChoose an option : "))
return choice
while choice != 2 :
choice = menu()
if choice == 1 :
do_this
elif choice == 2 :
print("This program will terminate.")
break
else :
print("Invalid option... ")
You are getting the return value in your while loop with the variable choice in the line choice = menu() Then you can use that value in your while loop.