Reputation: 207
So I have a Python assignment where I need to use a dictionary to hold the items of a menu, then randomly re-key and re-order the menu so that I can change the order of the menu options printed out. Here is an example of the code I have:
ChoiceOne = "Rekey Menu"
ChoiceTwo = "Quit"
menu = {'1':ChoiceOne, '2':ChoiceTwo,}
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
while userChoice not in menu.keys():
print("Invalid Input")
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
if menu[userChoice] == ChoiceOne:
menu = rekey(menu)
elif menu[userChoice] == ChoiceTwo:
quit()
The above code loops while the user chooses not to quit, repeatedly printing out the menu over and over again. The following is my rekey() function
def rekey(menu):
rekey = {}
keylist = random.sample(range(10), 2)
for i, item in zip(keylist, menu ):
rekey[i] = menu[item]
return rekey
My problem seems to present itself in the line where I check whether the user input for the menu option is valid or not. Initially, entering anything other than "1" or "2" will cause the program to enter the While loop until a valid input is entered. After rekeying the menu however, the line "while userChoice not in menu.keys()" is always triggered and no input is ever matched to continue the program.
I've tried to find the problem by printing out the new keys in the dictionary and checking to see if the userChoice matches any one of them, but even when I choose a valid new key, the program seems to think that nothing I enter is a valid key.
I hope I've described the problem well enough to be understood, thanks for the help in advance!!
Upvotes: 1
Views: 710
Reputation: 19329
According to the documentation the input(x)
function is equivalent to eval(raw_input(x))
. This means that typing "1" at the input prompt is equivalent to typing "1" in the python interpreter, so you get the integer 1.
As SpliFF has already pointed out, you need to ensure that you're either using integer keys in your menu dictionary, or you could use string keys for the dictionary and switch to using the raw_input
function to read the user's choice.
Upvotes: 1
Reputation: 38966
In your first case the menu keys are strings, after the rekey they are ints. You need to do a conversion of either the keys or the user input so they match.
Upvotes: 3