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


Groups > comp.lang.python > #6953

Re: Newby Python help needed with functions

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <jgardner@jonathangardner.net>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'own.': 0.03; 'elif': 0.04; 'mentioned,': 0.04; 'parameter': 0.05; 'sys': 0.05; 'subject:Python': 0.06; 'bits': 0.07; 'typed': 0.07; 'python': 0.08; '%s"': 0.09; '__name__': 0.09; 'all?': 0.09; 'condensed': 0.09; 'dict': 0.09; 'either.': 0.09; 'etc...': 0.09; 'none)': 0.09; 'none.': 0.09; 'none:': 0.09; 'skip:{ 20': 0.09; 'throw': 0.09; '>>>': 0.12; 'def': 0.12; 'error:': 0.12; 'am,': 0.14; 'wrote:': 0.14; '"__main__":': 0.16; 'called,': 0.16; 'explicitly.': 0.16; 'instance:': 0.16; 'intended.': 0.16; 'keyerror:': 0.16; 'repr()': 0.16; 'string:': 0.16; '\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0': 0.16; 'input': 0.17; 'cc:addr:python-list': 0.17; 'subject:help': 0.20; 'header :In-Reply-To:1': 0.21; 'figure': 0.21; 'so.': 0.22; 'cc:2**0': 0.22; 'assume': 0.23; 'cc:no real name:2**0': 0.23; 'away.': 0.23; 'keys': 0.23; 'received:209.85.210.174': 0.23; 'received:mail- iy0-f174.google.com': 0.23; 'fri,': 0.23; 'code': 0.24; 'values': 0.25; 'stored': 0.25; 'function': 0.25; 'string': 0.26; 'object': 0.26; 'tried': 0.27; 'message-id:@mail.gmail.com': 0.28; 'import': 0.29; 'jonathan': 0.29; 'cc:addr:python.org': 0.30; 'it.': 0.31; 'define': 0.31; 'calling': 0.31; 'print': 0.31; "skip:' 10": 0.32; 'andrew': 0.32; 'value.': 0.32; 'list': 0.33; 'actually': 0.33; 'asking': 0.33; 'lines': 0.33; 'error': 0.33; 'things': 0.33; "i've": 0.33; 'question': 0.34; 'skip:= 10': 0.34; '\xa0\xa0\xa0': 0.34; 'option': 0.35; 'skip:" 10': 0.35; 'defining': 0.35; 'like:': 0.35; 'skip:{ 10': 0.35; 'here,': 0.35; 'not,': 0.35; 'test': 0.35; 'options': 0.36; 'probably': 0.36; 'none': 0.37; 'received:google.com': 0.37; 'something': 0.37; 'received:209.85': 0.37; 'think': 0.38; 'but': 0.38; 'subject:: ': 0.38; 'doing': 0.39; 'should': 0.39; 'received:209': 0.39; 'returned': 0.39; 'subject:with': 0.39; 'really': 0.40; 'format': 0.40; 'your': 0.60; 'below': 0.61; 'you.': 0.62; 'lower': 0.64; 'here': 0.66; 'roughly': 0.67; 'accepts': 0.68; 'below:': 0.79; '(s):': 0.84; 'correctly?': 0.84; 'recognize.': 0.84
MIME-Version 1.0
Sender jgardner@jonathangardner.net
In-Reply-To <BANLkTinpQGQ0wtdkLuVegy_SmyvurQs-yg@mail.gmail.com>
References <BANLkTinpQGQ0wtdkLuVegy_SmyvurQs-yg@mail.gmail.com>
Date Fri, 3 Jun 2011 08:54:46 -0700
X-Google-Sender-Auth JuzzhZPKtb-liNinXagSKhx_bm4
Subject Re: Newby Python help needed with functions
From Jonathan Gardner <jgardner@deal-digger.com>
To Cathy James <nambo4jb@gmail.com>
Content-Type text/plain; charset=ISO-8859-1
Content-Transfer-Encoding quoted-printable
Cc python-list@python.org
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.2434.1307116489.9059.python-list@python.org> (permalink)
Lines 155
NNTP-Posting-Host 82.94.164.166
X-Trace 1307116490 news.xs4all.nl 49183 [::ffff:82.94.164.166]:34717
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:6953

Show key headers only | View raw


On Fri, Jun 3, 2011 at 7:42 AM, Cathy James <nambo4jb@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@deal-digger.com
http://deal-digger.com
1 (855) 5-DIGGER

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


Thread

Re: Newby Python help needed with functions Jonathan Gardner <jgardner@deal-digger.com> - 2011-06-03 08:54 -0700

csiph-web