Answer the question
In order to leave comments, you need to log in
How to make function execution by key from Python 3 dictionary?
There is a dictionary where each key is a letter and each value is a function. The user is prompted for a letter, how to execute the function that corresponds to the entered letter?
Example of non-working code:
def main():
while True:
key = str(input("Press R to read a file\nPress E to enter data\nPress L to leave the program\n"))
key = key.lower()
execute(key)
def execute(command):
return {
'r' : readfile(),
'e' : enterdata(),
'l' : exit()
}.get(command, "Command not found")
def readfile():
#Действия
def enterdata():
#Действия
def exit():
#Действия
main()
Answer the question
In order to leave comments, you need to log in
UPD: Hurrah, solved! I had to bang my head, but it turned out gracefully
def main():
while True:
key = str(input("Press R to read a file\nPress E to enter data\nPress L to leave the program\n"))
key = key.lower()
execute(key)
def readfile():
#Действия
def enterdata():
#Действия
dictOfCommands = {
'r': readfile,
'e': enterdata,
'l': exit
}
def execute(command):
dictOfCommands[command]()
main()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question