[Tutor] Local variables and functions

Don Arnold darnold02 at sprynet.com
Mon Nov 10 22:55:45 EST 2003


----- Original Message -----
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Ryan Smith" <rcsmith at speakeasy.net>
Cc: <tutor at python.org>
Sent: Monday, November 10, 2003 9:32 PM
Subject: Re: [Tutor] Local variables and functions


>
>
> On Mon, 10 Nov 2003, Ryan Smith wrote:
>
> >
> > def counterLetters(fruit):
> >  fruit = "bananna"
> >  count = 0
> >  for char in fruit:
> >  count = count + 1
> >  print count
> > print counterLetters(fruit)
>
> Hi Ryan,
>
> There's a small bug here: there's a "hardcoded" value for fruit here, on
> the line right below the 'def':
>
> >  fruit = "bananna"
>
>
> Any definition of counterLetters() probably shouldn't depend on a
> particular fruit.  It turns out that we can actually just yank it out:
>
> ###
> def counterLetters(fruit):
>     count = 0
>     for char in fruit:
>         count = count + 1
>     print count
> ###
>

<Snip> the rest of Danny's (typically) excellent response. When you execute
this function, you might notice something is still a little odd:

>>> print counterLetters("banana")
6
None
>>>

We expect to see the 6, but where does the None come from? You see, we're
really doing two things here: 1) calling counterLetters("banana"), and 2)
printing its result. The counterLetters() function prints its count value
within the function (the 6), but doesn't return a value (so its value is
None).  One small change will take care of this:

def counterLetters(fruit):
    count = 0
    for char in fruit:
        count = count + 1
    return count

>>> print counterLetters("banana")
6

All better.

HTH,
Don




More information about the Tutor mailing list