Answer the question
In order to leave comments, you need to log in
How to execute a function that I will define myself?
There are three functions:
def say(what):
print(what)
def sum(a, b):
print(a + b)
def connect(to):
print(f"You are connected to {to}!")
Answer the question
In order to leave comments, you need to log in
kirillinyakin suggested a more compact method, in turn I can offer you a modified version of your idea, where there will be no recursive error, and the sum will be for an independent number of numbers.
def say(what):
print(what)
def get_sum(*args):
items = [int(item) for item in list(*args)]
print(sum(items))
def connect(to):
print(f'You are connected to "{to}"!')
dict_func = locals()
print(dict_func['connect'])
while True:
request = input('Enter your request: ')
if 'say' in request and 'say' in request.split()[0]:
say(request.replace('say ', ''))
elif 'sum' in request:
get_sum(request.split()[1:])
elif 'connect' in request and 'connect' in request.split()[0]:
connect(request.replace('connect ', ''))
elif request == 'exit':
print('Goodbye!'); break
else:
print("I don't understand you, try again!")
Python has a locals() function that returns all variables in the current namespace, it remains only to iterate through this dictionary, where the key is the name of the variable, and the value is a reference to it, and check for a match between the names and that the value contains a function
The options proposed above are not bad, but they are strictly tied to specific functions and even their number. Add one more function - and you need to make changes to the script. What is not good.
There is another option. We write one auxiliary microfunction that will read the user's response and, depending on the first word, call a function whose name matches this word. To do this is relatively simple. But not everyone is familiar with such a cunning way.
Just:
def ExecIt(func, param):
return func(param)
request = input('Enter your request: ')
ExecIt(globals()[request.split()[0]], request.split(maxsplit=1)[1])
There are exec and eval functions, they run the passed text as code.
Example:
exec("sum(4, 5)")
result = eval("sum(4, 5)")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question