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


Groups > comp.lang.python > #6952 > unrolled thread

Re: Newby Python help needed with functions

Started byTim Chase <python.list@tim.thechases.com>
First post2011-06-03 10:18 -0500
Last post2011-06-03 10:18 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#6952 — Re: Newby Python help needed with functions

FromTim Chase <python.list@tim.thechases.com>
Date2011-06-03 10:18 -0500
SubjectRe: Newby Python help needed with functions
Message-ID<mailman.2433.1307114339.9059.python-list@python.org>
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)

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web