[Tutor] help, thanks very much.

Alan Gauld alan.gauld at btinternet.com
Wed Jan 16 09:34:32 CET 2008


"bill.wu" <bill.wws at gmail.com> wrote 

> i ask a easy question.
> 
> why the first one have"x",the second one 
> doesn't have "x". what is different? 

The first is using x as the name of a parameter
of the function and is only used inside the function.
The second one takes no parameter and relies on 
explicit knowlege that an variable called x 
exists in the global namespace.

The second form is considered bad practice 
unless you have a very good reason to use it
since it forces the function to know about 
things outside its control.

> when write "x",when don't write "x".

Using a parameter (usually called something 
more meaningful than x!) is normally the best 
way. Version 2 should be avoided if possible.

> in my point,the second one don't def variable.

Corect it uses the global variable defined 
at the module level. That is why the global 
statement is used.

> (1)
> 
> def func(x):
>    print 'x is', x
>    x = 2
>    print 'Changed local x to', x
> 
> x = 50
> func(x)
> print 'x is still', x (2)

This defines a global x with value 50.
It then calls func passing in the value 
50 to the parameter x which acts like a 
local variable, only seen inside the 
function.
The func internally assigns a value 
of 2 to that local x which does not 
affect the global x. It then prints 
the local value and exits
The next line of code then prints 
the global x to show that it has 
not changed.

If a different name had been used for the 
parameter it would be much clearer but 
I assume the author is trying to demonstrate 
how names are controlled.

def func(y):
   print 'y =',y
   y = 2
   print 'y =',y

x = 50
func(x)
print 'x =',x

The code here is identical in function 
to the first version but because we 
chose y as the parameter name it is 
obvious that they are different variables.

> def func():
>    global x
> 
>    print 'x is', x
>    x = 2
>    print 'Changed local x to', x

This function has no local variables and 
instead acts on the global x. It could 
be better written with a parameter like this:

def func(y)
    print 'y =',y
    y = 2
    print 'y=',y
    return y    # allows it to affect the global
 
> x = 50
> func()

And this line becomes

x = func(x)

> print 'Value of x is', x 

Now x will reflect the changes made by func()

You will find more about namespaces in the 
"Whats in a name?" topic of my tutorial.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list