FAQ
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!! ")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110603/7e61ecea/attachment.html>

Search Discussions

  • Andrew Berg at Jun 3, 2011 at 3:10 pm

    On 2011.06.03 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):
    """capitalize accepts a string parameter and applies the
    capitalize() method"""
    s.capitalize() ...
    f_dict = {'capitalize': 'capitalize(s)',
    Your capitalize() function doesn't return anything, therefore
    f_dict[capitalize] won't contain anything. Your string s will still be
    changed (inside the function) when the function is called, but there is
    still no value associated with capitalize().
    Also, capitalize in f_dict[capitalize] points to the capitalize function
    object instead of the entry in the dictionary. You should call
    f_dict['capitalize'] instead.
  • Tim Chase at Jun 3, 2011 at 3:18 pm

    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)
  • Jonathan Gardner at Jun 3, 2011 at 3:54 pm

    On Fri, Jun 3, 2011 at 7: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>
    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
  • Dave Angel at Jun 3, 2011 at 4:27 pm

    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

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedJun 3, '11 at 2:42p
activeJun 3, '11 at 4:27p
posts5
users5
websitepython.org

People

Translate

site design / logo © 2022 Grokbase