Reputation:
I have some validation checks for my menu which seem to be repeating the error message and I have spent so long staring at this error I seem to have gone blank!
I am running a file called student_class (not a class but just the file name) and as any menu validation if the user enters the incorrect choice I want it to display the error message and then re-display the menu etc etc.
The validation code is:
def ValidateMenuChoice(choice):
validchoice = False
Num = [1,2,3,4,5,6]
while validchoice == False :
if choice not in Num:
print("Invalid choice, please try again.")
display = menu.Menu("Student")
display.printMenu()
GetMenuChoice()
ValidateMenuChoice(choice)
else:
validchoice = True
return choice
Is there a simple mistake I am making or could it be more complex? Any help would be greatly appreciated.
GetMenuChoice function:
def GetMenuChoice(): #Gets users menu choice
MenuChoice = int(input())
print()
return MenuChoice
ANSWER EDIT:
Using a few answers below (thanks!) I had to just add main(choice) into my code as seen below:
def ValidateMenuChoice(choice=None):
Num = [1,2,3,4,5,6]
while True:
if choice not in Num:
print("Invalid choice, please try again.")
display = menu.Menu("Student")
display.printMenu()
choice = GetMenuChoice()
main(choice) #Added to make it work
else:
return choice
Thanks for the help :)
Upvotes: 0
Views: 164
Reputation: 18738
You are attempting both an iterative and a recursive approach, but you are not tracking your choice
and validchoice
variables properly.
For a proper recursive approach, get rid of your while
and add a return
:
def ValidateMenuChoice(choice):
Num = [1,2,3,4,5,6]
if choice not in Num:
print("Invalid choice, please try again.")
display = menu.Menu("Student")
display.printMenu()
choice = GetMenuChoice()
return ValidateMenuChoice(choice)
return choice
An iterative approach would look like this:
def ValidateMenuChoice(choice=None):
Num = [1,2,3,4,5,6]
while True:
if choice not in Num:
print("Invalid choice, please try again.")
display = menu.Menu("Student")
display.printMenu()
choice = GetMenuChoice()
else:
return choice
Upvotes: 0
Reputation: 122137
I think you need to make a simple tweak:
choice = GetMenuChoice()
At the moment, you never update choice
, so it recurses indefinitely.
More broadly, I would probably take an iterative approach, and avoid using a flag (validchoice
):
def GetValidMenuChoice():
display = menu.Menu("Student")
while True:
display.printMenu()
choice = GetMenuChoice()
if choice in range(1, 7):
return choice
else:
"Invalid choice, please try again."
Ideally, I would remove the hard-coded range(1, 7)
and make that dependent on the Menu
, but I can't tell from what you've posted whether that would be possible.
Upvotes: 2