[Tutor] From newbie. Defining Functions

alan.gauld@bt.com alan.gauld@bt.com
Wed, 14 Aug 2002 15:59:48 +0100


> I tried to figure out why the "print "in a_func
> a_var=",a_var"line outputs "15", Instead of "10" 

First you define some names(vaiables) and give them 
some values

> a_var = 10
> b_var = 15

Now you define a function that takes a parameter 
which coincidentally has the same name as one of 
the previously defined ones, although they are in 
no way related. It also creates a new name b_var 
which is only seen inside the function and is not 
related to the previously created variable.

> def a_func(a_var):
>     print "in a_func a_var = ",a_var
>     b_var = 100 + a_var
> ....
>     return b_var + 10

So b_var always retirns (a_var+100+10)

The function is now defined but hasn't been executed yet.

Now we call the function we defined passing b_var into 
the function so that the parameter (a_var) takes the 
value of variable b_var(15)

> c_var = a_func(b_var)

So c_var has been assigned the value returned by the 
function, namely a_var+110 = 125

Now we print out some values... None have changed 
except c_var which was reassigned by the function call.

> print "a_var = ",a_var
> print "b_var = ",b_var
> print "c_var = ",c_var

And try to print a name that has not been defined 
at this level.

> print "d_var = ",d_var
> 
> The output is: 
> a_var =  10
> b_var =  15
> c_var =  125
> d_var = 
> Traceback (innermost last):
>   File "separate.py", line 20, in ?
>     print "d_var = ",d_var
> NameError: d_var

Just as expected...

You might like to read the  "What's in a name" topic 
on my tutor...

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld