[Tutor] Calling functions
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 9 May 2001 16:41:54 -0700 (PDT)
On Tue, 8 May 2001, Timothy M. Brauch wrote:
> Is there a way to define a function and then use a raw_input to call
> the function?
Yes, you can use a dictionary that maps the name of a function to the
function itself.
> def func_0():
> do something here
>
> def func_1():
> do something else here
>
> dummy=raw_input('Which function do you want to execute? ')
Here's a little bit more code to make this work:
###
function_dict = {'func_0': func_0,
'func_1': func_1}
dummy = function_dict[
raw_input('Which function do you want to execute? ')]
dummy()
###
We can make this a little more bulletproof by checking to see if the
dictionary actually has the method we're looking for with has_key():
###
if function_dict.has_key(...):
# Then it's safe to call the function.
else:
# Let's force them to redo their input.
###
Hope this helps!