[Tutor] Local variables and functions
fredm at smartypantsco.com
Mon Nov 10 22:54:42 EST 2003
You have a few different errors, but first look at how you have defined the
variables 'fruit' in two different places:
* In the subroutine - as in def counterLetters(fruit)
* In the program calling the subroutine - as in print
counterLetters(fruit), here the name fruit is not actually defined!
First you have to understand how to pass values to subroutines and how
subroutines treat names:
If you have a subroutine defined by def counterLetters(fruit), then this
means that the subroutine expects you to pass it a variable (which can have
any name in the calling routine) and the subroutine will then deal with
that variable under the variable name 'fruit'.
So you can call that subroutine in any of the following ways:
fruit = 'banana'
apple = 'apple'
In each case the subroutine will take what you have given it and call it
The names of the variables passed to the subroutine are local to that
subroutine. You can use any name (even if it is in the global namespace),
and it will treat it as a separate instance.
Look at the following example:
print "My name is", name
name = 'Bill'
print "My name is", name
Once you run it, you should get the following output:
My name is Fred
My name is Bill
You can see from this that the variable 'name' in the main routine hasn't
changed, although in the subroutine 'myname' the variable 'name' has a
Looking at your example, you will see that in your subroutine you say:
- I will accept a variable called fruit as input to the routine,
- but then you define fruit to be 'bananna', no matter what the input!
Finally your calling routine is print counterLetters(fruit) .
This is wrong, as counterFruit subroutine does not actually return anything!
If you want a specific value to come back, you have to specify it as (for
Otherwise you have an implied "return None"
So the line print counterLetters(fruit) will print out 'None'
Your program should therefore be as follows:
count = 0
for char in fruit:
count = count + 1
fruit = "bananna"
Hope this helps,
At 09:54 PM 10/11/03 -0500, you wrote:
>I have been reading "How To Think Like a Computer Scientist" to learn how to
>program in python since I am a complete newbie. I am having problems with
>declaring variables. Namely when they are local to a function. Below is an
>example that I have been working on:
> fruit = "bananna"
> count = 0
> for char in fruit:
> count = count + 1
> print count
>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. 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.
More information about the Tutor