Reputation: 11
import os
name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "@" + server
def error(choice):
print(choice + ": command not found")
commands()
def clear():
os.system("cls")
commands()
def commands():
while 1 > 0:
choice = input(prompt)
{'clear': clear}.get(choice, error(choice))()
commands()
When running this code, no matter what I enter the dictionaries .get function always returns an error. When I enter 'clear' the script should go to that function. Does anyone have an idea why this does not work correctly? Thanks.
Upvotes: 0
Views: 2658
Reputation: 24153
You don't want to actually call error(choice)
.
You can partially apply parameters to a function but leave it to be called later:
>>> def error(choice):
... print(choice + ': command not found')
>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found
So you want:
{'clear': clear}.get(choice, partial(error, choice))()
Upvotes: 1
Reputation: 599788
You'll always see the error, because all arguments to a function must be evaluated before the function is called. So error(choice)
will be called to get its result before it is passed as the default value to get()
.
Instead, leave out the default, and check it explicitly:
result = {'clear': clear}.get(choice)
if result:
result()
else:
error(choice)
Upvotes: 3