Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6952

Re: Newby Python help needed with functions

Date 2011-06-03 10:18 -0500
From Tim Chase <python.list@tim.thechases.com>
Subject Re: Newby Python help needed with functions
References <BANLkTinpQGQ0wtdkLuVegy_SmyvurQs-yg@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2433.1307114339.9059.python-list@python.org> (permalink)

Show all headers | View raw


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)

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Newby Python help needed with functions Tim Chase <python.list@tim.thechases.com> - 2011-06-03 10:18 -0500

csiph-web