Newby Python help needed with functions

Jonathan Gardner jgardner at deal-digger.com
Fri Jun 3 11:54:46 EDT 2011


On Fri, Jun 3, 2011 at 7:42 AM, Cathy James <nambo4jb at gmail.com> 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>
>

This error is because the function capitalize is not a key in the f_dict dict.

> 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()

As Andrew mentioned, these functions return nothing when they are
called, which is probably not what you want.

>>> lower("ABCD")
(nothing)

You need to return the value you want the function to return explicitly.

def lower(s):
    return s.lower()

Note that your functions are just calling string methods. Why define
them at all? Just use the methods of the str. For instance:

>>> str.lower("ABCD"
'abcd'
>>> lower = str.lower
>>> lower("ABCD")
'abcd'

> def exit():
>     """ends the program"""
>     import sys
>     sys.exit()

you can just use sys.exit for exit, no need to define a new function
here either.

> if __name__ == "__main__":
>     f_dict = {'capitalize': 'capitalize(s)',
>           'title': 'title(s)',
>           'upper': 'upper(s)',
>           'lower': 'lower(s)',
>           'exit': 'exit(s)'}

I think this is where things go really bad for you.

You are defining a new dict here, f_dict. It has keys that are the
strings 'capitalize', 'title', etc... These have values that are
strings 'capitalize(s)', etc...

I doubt this is what you want.

Don't you want the values to be the functions corresponding to the
names in the keys? If so, just tell Python so.

f_dict = {'capitalize', str.capitalize, ...}

>     options = f_dict.keys()
>     prompt = 'Enter a function name from the list (%s): ' % ',
> '.join(options)

Note that you can use %r to format the repr() of the value.

prompt = 'Enter a function name from the list %r: ' % (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!! ")

Here is where things are also probably not what you intended. What you
are asking Python to do is:

1. Test if f_dict has a key that is the function capitalize; if so,
call capitalize on s and throw the result away.
2. If not, then test if f_dict has a key that is the function title;
if so, call title on s and throw the result away.
etc...

First, you can use the dict to retrieve the function you've stored as
the value in the dict.

fn = f_dict.get(inp, None)

That returned value is actually callable! That is, you can then do
something like:

fn("This is the input string")

Of course, as you already know, you should test fn to see if it is
None. If so, they typed in an option you don't recognize.

Secondly, what are you doing with the formatted string? I assume you
want to print it. If so, be explicit.

The above lines can be roughly condensed down to:

f_dict = {'capitalize':str.capitalize, ...}
while True:
    inp = input(prompt)
    fn = f_dict.get(inp, None)
    if fn is not None:
       s = input("Input a string: ").strip()
       print "Output is: %s" % fn(s)
    else:
        print "Please input a valid selection"


Since this is homework, I've purposefully left important bits out that
you should be able to figure out on your own.


-- 
Jonathan Gardner
jgardner at deal-digger.com
http://deal-digger.com
1 (855) 5-DIGGER



More information about the Python-list mailing list