[Tutor] Local variables and functions

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 10 22:32:39 EST 2003



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
###

This'll still work because the input to counterLetters is a "fruit" ---
counterLetters expects to take a fruit in when we call it.


By the way, if we call counterLetters() with too few fruits:

###
>>> counterLetters()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: counterLetters() takes exactly 1 argument (0 given)
###


or too many fruits:

###
>>> counterLetters("apple", "banana", "squash")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: counterLetters() takes exactly 1 argument (3 given)
###


Python will say something fruity about it.



> If I make the fruit variable global the function works, however when I
> have it local to the function, I get a
>     print counterLetters(fruit)
> NameError: name 'fruit' is not defined, error message.

Hmmm... try something like:

    print counterLetters("apple")
    print counterLetters("breadfruit")

We can even say something like:

    a = "apple"
    b = "breadfruit"
    print counterLetters(a)
    print counterLetters(b)
    print counterLetters(a + b)

Do you see how the last example "print counterLetters(a+b)" works?


> Can someone please point out what I maybe missing?  The concept of local
> variables seems pretty straight forward, but I have been struggling with
> this issue since the 4th chapter.  I tried searching on google to see if
> someone else was having a similar problem, but to no avail.

That's what the Tutor list is for.  *grin*

Please feel free to ask more questions about this; we'll be happy to point
to toward more examples to make the concepts clearer.


Good luck to you!




More information about the Tutor mailing list