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!!
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.
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.
Related
I want to create a simple game in Python 3.8, and i need to verify an entry`s input in order to create it. Something like this:
if input.text == "":
print("Error")
but i don`t know how to do this in Python. I used to do that a lot in C# but here it s not that easy apparently.
Considering you are talking about an Entry and also have the Tag tkinter in your question I assume you want to get some user input from a tkinter Entry widget.
To get a value from a Entry widget you can use the get() method. This returns a string.
You can use a simple button command or a bind() to call a function that then checks the value of the entry field.
You can also throw in a strip() just in case the user uses a space or two without imputing anything else. This way a string of spaces still returns back as an error.
Here is a simple example:
import tkinter as tk
def check_entry():
value = entry.get().strip()
if value == '':
print('Error')
else:
print('Value is not an empty string. Now do something.')
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text='Check Entry', command=check_entry).pack()
root.mainloop()
To get an input, you can use the input function. This will automatically return a string. Here is sample usage of this:
user_input = input("Please put your input here: ") # Get user input
if user_input == "": # Compare input to empty string
print("Error")
You can see the Python docs for more information about input.
Try with:
# get the input using the input built-in function
user_input = input("insert your input here: ")
# check the input
if user_input == "":
# raise an exception and stop the program
raise ValueError("invalid input! Empty string")
ent = input("Press the Enter key to spin the roulette wheel.")
if ent == "":
print("Roulette wheel spinning...")
print("Roulette wheel spinning...")
else:
#I want it to do nothing till only enter is hit What can I write here?
Is there way so when a key other than enter alone is pressed that it wont do anything until only enter is pressed? Using input allows the users to write something and therefore when they hit enter it will always run through. I'd prefer it if I can disable the writing and only respond when the enter key is hit.
You could put a while loop around the input so until the input equals enter the user can't continue. For example:
while True:
ent = input("Press the Enter key to spin the roulette wheel.")
if ent == "":
break
print("Roulette wheel spinning...")
print("Roulette wheel spinning...")
Hope this could help.
I have tried to find what I am seeking before posting this. But I have a hard time formulating the question and finding an answer.
I wonder if there is any way of having a key, such as "b", that takes the user back to the main menu where ever he is while running my program.
I have a menu and sub-menus and I want the user to be able to go back to the menu wherever he is by just pressing "b". I wonder if there is any easy way of doing this instead of putting
if choice= b:
menu()
whenever I have an input()...
I hope this is not too confusing! Would really appreciate a answer!
Not recommended for making your code easy to read but...
You could make your 'b' input check a function, then run that function at the start of each input check
def b_check(option):
if option == 'b':
main_menu()
else:
return option
def main_menu():
#your main menu function goes here
#your active menu code goes here
#ask the user to make their selection
#Note: for Python 2.x use `raw_input`
option = input('Enter your choice')
b_check(option)
if option == 'a':
#do this
elif option =='c':
#do that
I'm playing around trying to emulate some Ctrl-P-like behaviour in Vim. What I have so far:
User calls my function.
A window is opened with a list of items in it.
A prompt is displayed under the list of items.
I want the user to be able to use the up and down arrows to select from the items but without leaving the prompt (in which they can also type).
I have got 1-3 mostly under control but am struggling with #4. I have got as far as this:
python << EOF
import vim
def MyWindow():
# Create a new window at the bottom
vim.command("below new")
vim.current.buffer.append("123")
vim.current.buffer.append("234")
vim.current.buffer.append("345")
vim.command("redraw")
vim.command("setl cursorline")
vim.command("echon '>> ' | echoh None")
while True:
vim.command("let x = getchar()")
character_code = vim.eval("x")
if character_code == "13":
# Exit by pressing Enter
break
elif character_code == "\x80kd": # Down
vim.command("keepj norm! j")
vim.command("redraw")
EOF
command! MyWindow python MyWindow()
Now the first down arrow keypress works perfectly, but subsequent down arrow kepresses don't, even though the code in the "if down key pressed" case is executed. Any ideas?
I just realised I can make it work by doing this:
elif character_code == "\x80kd": # Down
vim.command("keepj norm! j")
vim.command("setl cursorline") # <-- This fixed it
vim.command("redraw")
But I have no idea why or if this is a sensible thing to do.
I am trying to create a task based on the Dragon Realm game in the Invent your Own Games with Python book. The original allows one choice to be made and uses functions to set up those choices. I am trying to allow two separate choices to be made but can't figure out how to stop the task after the first choice if the def statement gives a specific result, ie. if the first choice is the wrong choice then the user does not get to make a second choice. Any help would be much appreciated. Thanks.
import random
import time
def displayIntro():
#introduction
def chooseDoor():
#user chooses door
def checkDoor(chosenDoor):
#checks user choice against random number
if chosenDoor == str(friendlyDoor):
#various good stuff happens
else:
#bad stuff happens
#at this point I would like to go back to the option to play again if they have chosen the wrong door
#but I can't make it work by putting a break here as it goes on to the next def statement (chooseBox)
#this is where the original game finished
def chooseBox():
#user chooses a box but only if they made the correct choice above
def checkBox(chosenBox):
#checks user choice against random number and good or bad stuff happens
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
doorNumber = chooseDoor()
checkDoor(doorNumber)
boxNumber = chooseBox()
checkBox(boxNumber)
#play again option
The checkDoor() function should return a True if a friendly door is chosen, False if not. Then, in your main loop, modify
checkDoor()
to
if not checkDoor():
continue
In this way, is the player chooses a non-friendly door, the function returns False, and the "continue" statement will reset the program to the next execution of the while loop. Otherwise, it goes on to chooseBox()