Menus Looping on Python - python

for an assignment, I made a menu and must have it work in a way to execute multiple functions. However, the problem is that when I use the menu and put in an answer that doesn't exist, I cannot get it to work correctly. So when I re-enter an option number for "Incorrect option, try again: ", I do not get the number re-evaluated to execute. Since my code is far from finished, right now I want to be able to choose "4" as an input and get "Incorrect option, try again" as an output and input "1" into this to get the output "Choose the level of difficulty".
def main_menu():
print(10*"=","GAME",10*"=",'\n')
print("1. Choose level of difficulty ")
print("2. Start Game")
print("3. Exit the Game",'\n')
print("Current Difficulty: /5")
print("Highest Score Reached:",'\n')
option=input("Enter an option: ")
return option
def user_input():
while True:
try:
if option==1:
difficulty()
break
elif option==2:
start()
break
elif option==3:
exit()
break
except:
option=input("Incorrect option, try again: ")
def difficulty():
d=int(input("Choose level of difficulty: "))
if 1<=d<=5:
start()
else:
int(input("Incorrect option, try again: "))
#difficulty()
return d

Here a is modified version of your code which I believe does what you are looking for.
def main_menu():
print(10 * "=", "GAME", 10 * "=", '\n')
print("Current Difficulty: /5")
print("Highest Score Reached:", '\n')
while True:
print("1. Choose level of difficulty")
print("2. Start Game")
print("3. Exit the Game", '\n')
try:
option = int(input("Enter an option: "))
if option == 1:
difficulty()
elif option == 2:
start()
elif option == 3:
return
else:
print("Incorrect option, try again!")
except ValueError:
print("Invalid option.")
def difficulty():
try:
d = int(input("Choose level of difficulty: "))
if 1 <= d <= 5:
print(d)
start()
else:
print("Incorrect option, try again.")
except ValueError:
print("Invalid value.")
def start():
print("Starting game...")
if __name__ == "__main__":
main_menu()
Let me know if anything is misunderstood or mistaken.

Related

If statement not executing. Python

I am still new to programming and I wanted to do a simple calculator in python. However, I could only reach this point of my code:
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
float(variableA)
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
float(variableB)
break
else:
print("Incorrect input. Please try again.")
continue
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
Not sure why my if statement is not executing after all the correct inputs from the user. I mostly focused on the error handling part and after everything going well, the if statement is just not executing after that. There could probably be a simple mistake but even I can't understand what's going on here.
You have an issue with type casting. So when you are taking input from the user all the userInput is str not int, so you need to cast it like userInput = int(userInput) before doing further calculator operations.
Also, you need to assign the float casting to a variable like this variableA = float(variableA) and variableB = float(variableB) otherwise your add/sub/divide/multiply etc. will not do expected operations.
For example add will do concatenation i.e '2' + '4' = 24 not 2 + 4 = 6.0
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
variableA = float(variableA) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
variableB = float(variableB) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
userInput = int(userInput) # <-- fix this line
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
If the user input is supposed to be an int, convert it early and fail fast.
while True:
userInput = input(...)
try:
userInput = int(userInput)
except ValueError:
print("Not an integer, try again")
continue
if userInput in range(1, 7):
break
print("Number out of range, try again")
and similarly for the operands
while True:
variableA = input("Enter the first value: ")
try:
variableA = float(variableA)
break
except ValueError:
print("not a float")
There's little reason to convert the menu choice to an integer, though. You could simply write
while True:
userInput = input(...)
if userInput in "123456": # ... in ["1", "2", "3", "4", "5", "6"]
break
print("Invalid choice, try again")

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)

Try Except Block not passing after correct input

I'm new to Python and coding in general, and ran into a bit of a bug in my code. Whenever i type in the wrong input in my Try/Except code block, the console prints "Invalid input" However, whenever i type in the correct phrase in the console, it still says "Invalid input". I looked online to try to fix this issue (notated with ##) with these lines of code, but i still get the same issue.
For example, I would type in "Mad Libs" with correct case and everything, and still get "Invalid input" from my != command. Could this be easily fixed by formatting in a different way? This happens with all 3 games.
How can this issue be addressed? Thanks in advance!
def game_selection(): ##
pass ##
while True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
game_selection() ##
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
Because you asked it to answer invalid input anyway in this code
While True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
The thing is, this code will not work because if I enter "Mad Libs" the first if will not pass and so it will pass to all the others elif. So you can't take this approach.
What I advice you to do is to check if the playerChoice string is in an array
from time import sleep
while True:
playerChoice = input("So, which game would you like to play?:")
allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
if playerChoice not in allowedGames:
print('Invalid input!')
else:
break
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

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

Categories

Resources