This type of question comes up a lot on StackOverflow and is most often the result of people not really getting the difference between data and code.
You typically don't want users of your program to have to know what the code of the program is to be able to use it.
So, instead of magically calling a()
when the string 'a'
is entered, it's generally better to code explicitly that a()
will be called with 'a'
is entered.
Here's some code explaining the difference:
def a():
print('running a')
def b():
print('running b')
def c():
print('this should not be run!')
choice = input('a or b?')
if choice == 'a':
a()
elif choice == 'b':
b()
choice = input('a or b?')
eval(f'{choice}()')
Note how only 'a'
or 'b'
do something after the first prompt, but you can enter 'c'
on the second prompt, even if you would only ever want the user to run a
or b
.
Even worse, what do you think happens if the user enters wipe_my_c_drive
and you happen to have a function that does just that?
Also, if you later replace your function a()
with a new function called new_a()
, your program can work the same for your users if you use the first method, while the second method requires your user to know the name has changed.