Newby Python help needed with functions

Dave Angel davea at ieee.org
Fri Jun 3 12:27:47 EDT 2011


On 01/-10/-28163 02:59 PM, 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>
>
> Code below:
>
>
>
> def capitalize (s):
>      """capitalize accepts a string parameter and applies the capitalize()
> method"""
>      s.capitalize()
> def title(s):
>      """accepts a string parameter and applies the title() method"""
>      s.title()
> def upper(s):
>      """accepts a string parameter and applies the upper() method"""
>      s.upper()
> def lower(s):
>      """accepts a string parameter and applies the lower() method"""
>      s.lower()
> def exit():
>      """ends the program"""
>      import sys
>      sys.exit()
> if __name__ == "__main__":
>      f_dict = {'capitalize': 'capitalize(s)',
>            'title': 'title(s)',
>            'upper': 'upper(s)',
>            'lower': 'lower(s)',
>            'exit': 'exit(s)'}
>      options = f_dict.keys()
>      prompt = 'Enter a function name from the list (%s): ' % ',
> '.join(options)
> while True:
>      inp = input(prompt)
>      option =f_dict.get(inp, None)#either finds the function in question or
> returns a None object
>      s = input ("Enter a string: ").strip()
>      if not (option):
>          print ("Please enter a valid selection")
>      else:
>          if f_dict[capitalize]:
>              capitalize(s)
>          elif f_dict [title]:
>              title(s)
>          elif f_dict[upper]:
>              upper(s)
>          elif f_dict [lower]:
>              lower(s)
>          elif f_dict[exit]:
>              print ("Goodbye!! ")
>

You have a number of things wrong here.  The most obvious is that 
capitalize, which is a function object, cannot be used as a key in the 
dictionary.  That's okay, because the actual keys in your dictionary are 
strings, like 'capitalize'.

But there are more fundamental things wrong.  You should test each piece 
before worrying about the program as a whole.  The functions like 
capitalize, as written, do nothing useful.  They don't return a value, 
they can't modify their argument (assuming their argument is a string, 
which is immutable).  You probably wanted a return statement in each of 
them.

After each function, add lines like

print capitalize("Howdy Doody")

to see that it returns something reasonable.  You can remove those 
prints after it all works.

Next, you have a dictionary of dubious purpose.  Probably you meant for 
it to have a mapping from string to function, but it's just from string 
to string.

Next, in your else clause, you are looking up const values in the 
dictionary (or at least will if you change to the literals I suggested 
above).  So you'll always match on the first one.  Somehow you have to 
use either inp or option in those tests, if you want to do different 
things based on the token that was input.

I suspect you meant to store function objects as values in the 
dictionary, in which case option will be a function object.  If that's 
the case, then the else clause doesn't need any additional tests, it can 
just call the function object, passing it the string object s.

Finally, you probably want to have some output, in each of those cases. 
If you changed the functions as I suggested, you might replace the whole 
else clause with:

       else:
            print option(s)

HTH,
DaveA





More information about the Python-list mailing list