I am a complete beginner in learning Python. Currently working on an assignment and having issues in creating menu with submenus.I am trying to connect functions properly and make my program work.
How can I make my submenu work? Output doesnt show the submenu options.
type def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
display_header()
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I might be wrong in understanding the code, but here's what I think's happened.
when you call your invitees_menu function it immediately calls itself. This breaks a rule of recursion (a function calling itself) and causes an infinite loop of just calling the start of the function over and over again. Which gives us this error:
RecursionError: maximum recursion depth exceeded
So first i'd remove the first invitees_menu line completely. Then in the while loop you're calling the invitees_menu again. This is again the same problem because each time you call the function, it will call itself again and never get to returning any item. Here i've replaced it with:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
You then have the problem of never actually leaving the while True loop. Since entering B should break out and then go back to the main loop in the __main__ call, so i replaced the display_header with break.
Finally, the last few smaller things are:
removing the "type" at line 1
moving the display header in main inside the while loop
fixing up the irregular tab structure in invitees_menu
And here it is
def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
while True:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
break
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I suggest as first step to clean up the mess with recursive function calls in following section:
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
Next step in cleaning up the mess would be to remove the entire unnecessary parts of the code preventing the sub-menu from showing up when calling invitees_menu().
Related
Can anyone help I am a beginner? I want the variable choice to be displayed after the menu is but I need the variable to be on top so the name inserted can be shown beside add player name.
choice = input("Input your menu choice: ")
choice = False
if choice == "1":
name = input("What is your name? ")
print(" Menu ")
print("------------------------------------------")
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print("------------------------------------------")
choice True
I tried to use a Boolean but it didn't so any help would be great.
How about defining a string first like this?
import random
name = 'Anonomous'
playing = True
while playing == True:
print(" Menu ")
print("------------------------------------------")
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print("------------------------------------------")
choice = input("Input your menu choice: ")
if choice == "1":
name = input("What is your name? ")
if choice == "2":
winner = False
capital_city = random.choice(['London', 'Paris', 'Rome'])
while not winner:
guess = input("What capital city am I thinking of? ").title()
if guess == capital_city:
print(f'You won!!! I was thinking of {guess}..')
winner = True
else:
print(f'No, it was not {guess}, guess again..')
if choice == "3":
playing = False
This part:
choice = input("Input your menu choice: ")
choice = False
will make choice always equal False, also you should avoid changing types of variables like above: from str to bool. Assuming that you want working and well-structured console game:
name = 'Unnamed' # Set default value of name.
# Create game loop using infinite while.
while True:
# Display the menu: use string multiplication and a little of math.
print(' ' * 18 + 'Menu' + ' ' * 18)
print('-' * 40)
print(f"[1] Add player name: {name} ")
print("[2] Play guess the capital city")
print("[3] End game")
print('-' * 40)
# Get choice from user.
choice = input("\nInput your menu choice: ")
# Perform proper action for a choice selected.
if choice == '1':
name = input("What is your name? ")
elif choice == '2':
# Load your game ...
...
# If player wants to end game, it is equivalent to exiting
# loop using 'break' statement.
elif choice == '3':
break
else:
# Define what happens if player inputted unsupported choice.
...
# It is a common way to clear screen in python console
# applications/games, if fourty lines of empty lines is not
# sufficient increase amount of them.
print('\n' * 40)
# Here you can save for instance player score or nickname and
# later read it at the beginning of file (before the game loop).
I'm trying to create a sort of CLI menu in Python (very new to this) and having an issue with the quit option mostly, it won't actually quit and jumps to the "Oooops that isn't right" option instead, or repeats the last step. It does seem to work if you put it as the first choice though
I know I must be doing something daft. I've tried just putting the variable at the end of the function, as well as the menu function itself but that didn't seem to work.
Snippet below if anyone can point me in the right direction.
def my_menu():
choice = input("Please choose an choice: ")
choice = choice.lower()
while (choice != "quit"):
if choice == "b":
a_thing()
my_menu()
if choice == "quit":
break
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
Try to input the choice another time at the end of the loop, remove the call to the my_menu() function and remove the if choice=="quit" block (because the loop will automatically quit when the choice is set to "quit")
def my_menu():
choice = input("Please choose an choice: ").lower()
while (choice != "quit"):
if choice == "b":
a_thing()
else:
print("Oooops that isn't right")
choice = input("Please choose an choice: ").lower()
def a_thing():
print("a thing")
my_menu()
Or you can remove the loop and just verify using if statements and in the case of "quit" you just put return to break the loop
def my_menu():
choice = input("Please choose an choice: ").lower()
if choice == "b":
a_thing()
elif choice == "quit":
return
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
I ran your code, and on its first iteration it runs as expected. After that, the recursive call to my_menu() starts to cause problems.
Walking through it, first you enter some random string, "hi", and it will enter the while loop and use the else case. This will call my_menu(), which then calls another while loop. When you enter that new while loop, any exiting that you do (e.g. break) won't exit the first loop, only the loop that your currently in, so you're in an infinite loop because you can never "go back" and change the value of choice in the first loop.
A way you could achieve this behavior with the least amount of changes to your code would be like this:
def my_menu():
choice = ""
while (choice != "quit"):
choice = input("Please choose an choice: ")
choice = choice.lower()
if choice == "b":
a_thing()
if choice == "quit":
break
else:
print("Oooops that isn't right")
def a_thing():
print("a thing")
my_menu()
(I removed your recursive calls to my_menu(), moved the input lines to within the loop, and initialized choice before the loop)
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")
I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==NamesArray[position]):
print("Name is: " +position)
break
if position>5:
print("The account number not found!")
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
When the user enters "P" it is supposed to call to def PopulateAccounts() and it does, but the problem is that it doesn't stop and the user keeps having to input account name, account number, and account balance. It is supposed to stop after the 5th name. How do I fix this?
It's because after PopulateAccounts() finishes while loop keeps iterating because choice is still P. If you want to ask user for another action simply ask him again for input.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
choice = input("Please enter another action: ")
Also I'd recommend you use infinite loop to keep asking user for inputs, and break out of it when user enters 'E', this way you could also track invalid inputs.
while True:
choice = input("Please enter your choice: ")
if choice == "P":
PopulateAccounts()
elif choice == "S":
SearchAccounts()
elif choice == "E":
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid action \"{}\", avaliable actions P, S, E".format(choice))
print()
Your code asks for the user's choice only once -- before the loop begins. Because it never changes, that loop will stick with the user's choice for an infinite number of iterations.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
# here at the end of this loop, you should
# get the user to enter another choice for the next
# iteration.
Your while loop has no counter to make it stop at the 5th name, and position only exists during the execution of the function that it is in. Also, position will never be greater than 4. range(5) starts at 0 and ends at 4.
Your for loop is fine. The problem is that your while loop is repeating. So after PopulateAccounts() is called, it correctly finishes after running through the for loop 5 times, but since choice is still equal to "P" (this hasn't been changed after the user first enters it), you still remain in the while loop, which means PopulateAccounts() will be called again and again. You can verify this by sticking an additional statement like "print("Hey, we're at the top of the While loop!")" after the "while" line.
Try rewriting your while loop with an explicit break if the user selects "E":
while True:
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
quit()
choice = input("Please enter either P, S or E: ")
Note that this extra input at the bottom also conveniently appears if the user typed something else besides "P", "S", or "E". You may also want to consider adding .upper() to the choice checks to make it case insensitive.
# For updating the version!
version = "0.1"
# For game start!
from choice1 import choice1
# insert import functions from checkpoints choices here!
def gamemenu():
print("Welcome to the RTG!")
# Starts the game
print("1. START!")
# Goes to an earlier checkpoint
print("2. CHECKPOINTS!")
# Views the "about' page
print("3. ABOUT")
# Shows my website address!
print("4. INFO ABOUT CREATOR")
# Exits the game
print("5. EXIT")
# The user input!
option = input("Make your choice, buddy! "
if option == "1":
choice1()
# elif option == "2":
# Not added yet
elif option == "3":
print("Random Text RPG, version %s" % version)
print("This is just a random game made by me for fun")
print("Please dont't take offence :(")
elif option == "4":
print("Made by Lightning Bolt."))
elif option == "5":
break
else:
print("ERROR: invalid option")
menu()
menu()
Hello everyone,
I am a beginning programmer and I have encountered a problem which I am inable to solve. When I run my program in the Python 3 shell it says invalid syntax and marks the ":" in line 1 red, which means that there is something wrong there. With all other if/else/ifelse statements it doesn't say that the : is invalid syntax. If I remove the ":" it marks choice1() in red for improper syntax, while it's indented with exactly 4 spaces.
I really have no idea what's wrong with the code, thanks for anyone who helps me!
here is a screenshot: http://imgur.com/wuWMa0L (indentation and such)
Close the parenthesis on the line that gets input from the user
Remove the extra parenthesis under elif option == "4"
Remove the break statement, there's no loop there
Code:
# For updating the version!
version = "0.1"
# For game start!
from choice1 import choice1
# insert import functions from checkpoints choices here!
def gamemenu():
print("Welcome to the RTG!")
# Starts the game
print("1. START!")
# Goes to an earlier checkpoint
print("2. CHECKPOINTS!")
# Views the "about' page
print("3. ABOUT")
# Shows my website address!
print("4. INFO ABOUT CREATOR")
# Exits the game
print("5. EXIT")
# The user input!
option = input("Make your choice, buddy! ") #you missed a closing parenthesis here :D
if option == "1":
choice1()
# elif option == "2":
# Not added yet
elif option == "3":
print("Random Text RPG, version %s" % version)
print("This is just a random game made by me for fun")
print("Please dont't take offence :(")
elif option == "4":
print("Made by Lightning Bolt.") # there was an extra paren here
elif option == "5":
pass #as #Padraic mentioned, there should be no break statement
else:
print("ERROR: invalid option")
menu()
menu()