[Tutor] Just need to check a basic understanding of global statement

Alan Gauld alan.gauld at yahoo.co.uk
Tue Sep 29 04:03:10 EDT 2020


On 29/09/2020 03:49, Manprit Singh wrote:

> def swap():
>     global x                # Makes x as global variable,
>     global y                # Makes x as global variable
>     x, y = y, x              # swaps the values
> 
> x = 3
> y = 5
> swap()
> print(x, y)
> 
> will give x = 5, y =3

Yes it will.

> Can you term this example as an appropriate use of global statement?

Its appropriate in the sense that you want to use the x,y declared
outside the function. But the swap function would be better written by
taking those values as parameters.

def swap(x,y): return y,x

x = 3
y = 5
x,y = swap(x,y)


> Here x & y should not be used before their global statements nor should
> they appear as formal parameters  in function definition.

x and y can be used as much as you like both before and after the
global statement. global has no impact on code outside the function.
Similarly you can use the names x,y as formal parameters to
functions and those functions will use the parameters as
local variables (unless you also used global inside the function).

def add(x,y): return x+y   # x,y local to add()

global does nothing except make names outside the function
usable in assignments inside the function. In some sense it
works like an import statement at the module level. It
could be thought of as if it were written:

def swap():
   from global import x,y   #hypothetical only, it wont work!
   y,x = x,y

where global is the current module.

But plain global is simpler...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list