On 06/03/2011 09:42 AM, Cathy James wrote:
I need a jolt here with my python excercise, please somebody!! How can I
make my functions work correctly? I tried below but I get the following
error:

if f_dict[capitalize]:

KeyError:<function capitalize at 0x00AE12B8>

def capitalize (s):

Here you define the variable "capitalize" as a function.

     f_dict = {'capitalize': 'capitalize(s)',

Here your dictionary's key is a *string* "capitalize" (not the variable defined above)

         if f_dict[capitalize]:

Here you use the function variable as an index into this dict, not the string (which is the key that the dictionary contains).

Changing this to

  if f_dict["capitalize"]:

it will find the item. Note that you'd have to change the other keys too.

Finally, note that Python allows you to do function dispatch, collapsing your entire if/elif tree to something like

  f_dict = {# map of strings to the function-variable name
    'capitalize': capitalize,
    ...
    }
  option = f_dict.get(inp, None)
  if option is None:
    do_whatever_error_processing(inp)
  else: # "option" is the function so we can call directly
    option(s)

-tkc

(sorry if a dupe...got an SMTP error)

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to