Loop keeps returning to wrong part [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I'm taking a fundamentals of programming class and we're supposed to be building a menu that calculates BMI and also shows different gym membership options, what I can't figure out is why my menu keeps looping back to the BMI calculator after viewing the membership rates.
this is some of my code:
def mainmenu():
option = int(input("Enter your option: "))
while option != 0:
if option == 1:
try:
print("Calculate BMI")
the_height = float(input("Enter the height in cm: "))
assert the_height > 0
the_weight = float(input("Enter the weight in kg: "))
assert the_weight > 0
the_BMI = the_weight / (the_height/100)**2
except ValueError:
print("Enter height and weight in whole numbers")
print("Your BMI is", the_BMI)
if the_BMI <= 18.5:
print("You are underweight.")
elif the_BMI <= 24.9:
print("You are Normal.")
elif the_BMI <= 29.9:
print("You are overweight.")
else:
print("You are obese.")
check = input("Do you want to quit or start again, enter Y to restart or another to end ?: ")
if check.upper() == "Y":
print("Bye...")
mainmenu()
elif option == 2:
def submenu():
print("Choose your membership type")
print("[1] Bassic")
print("[2] Regular")
print("[3] Premium")
print("[0] Exit to main menu")
loop = True
while loop:
submenu()
option = int(input("Enter your option: "))
if option == 1:
print("Basic Membership")
print("$10 per week, $40 per month")
break
elif option == 2:
print("Regular Membership")
print("$15 per week, $60 per month")
check = input("Do you want to quit or start again, enter Y to restart or another to end ?: ")
if check.upper() == "Y":
submenu()
elif option == 3:
print("Premium Membership")
print("$20 per week, $80 per month")
check = input("Do you want to quit or start again, enter Y to restart or another to end ?: ")
if check.upper() == "Y":
submenu()
elif option == 0:
loop = False
else:
break
else:
print("Invalid option....")
break
mainmenu()
option = int(input("Enter your option: "))
Any suggestions would be helpful, I've been playing around for a while and can't find the solution.

It looks like the reason for this is that you're using option variable to store the value that user provide for both main menu and sub menu.
Instead of this
submenu()
option = int(input("Enter your option: "))
Use
submenu()
submenu_option = int(input("Enter your option: "))
Also replace the option with submenu_option only where you wants to refer to the user selection for the sub menu

Related

I cannot pass a parameter inside a function to another function (Python)

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)

Syntax errors, infinite loops and a bunch of formatting issues

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()

How do I fix my Python function so that it returns with input prompts?

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:
...

python ATM loop trouble

I have written this program and cant seem to figure out how to get the program to loop back to the beginning and ask the 'choice' option again.
The program runs fine, everything prints to the screen, even the part that asks if you would like another transaction, how do I get this to loop back?
Write ATM program. Enter account balance, print beginning balance.
ask for deposit or withdrawl, depending on selection, call function
to perform the action they wish, then print new balance. (Use iteration)
def withdraw():
amt = int(input("What amount to withdraw - multiples of $20: "))
print('New balance: $', balance - amt)
def deposit():
amt = int(input("How much are you depositing? "))
print('New balance: $',balance + amt)
def bal():
return(balance)
print ("Hello, Welcome to Python ATM.")
balance = float(65.01)
pin = int(input("please enter your account number (Any number:) "))
print('''Current balance: $''',balance)
choice = int(input('''
Please choose an option from the following:
1 - Withdraw
2 - Deposit
3 - Check Balance
4 - Exit: '''))
if choice == 1:
print(withdraw());
elif choice == 2:
print(deposit());
elif choice == 3:
print(bal());
more = input("Would you like another transaction? (y/n)")
Maybe you need a loop to repeat the choice :
while True:
print('''Current balance: $''',balance)
choice = int(input('''
Please choose an option from the following:
1 - Withdraw
2 - Deposit
3 - Check Balance
4 - Exit: '''))
if choice == 1:
print(withdraw());
elif choice == 2:
print(deposit());
elif choice == 3:
print(bal());
more = input("Would you like another transaction? (y/n)")
if more.lower() != 'y':
print("Goodbay")
break

PYTHON: Unable to loop properly

EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")

Categories

Resources