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

Mark Lawrence breamoreboy at gmail.com
Tue Sep 29 04:10:01 EDT 2020


On 29/09/2020 03:49, Manprit Singh wrote:
> Dear sir ,
> 
> Kindly consider a problem, in which i have to write a function that swaps
> values of two variables , I have written the code like this :
> 
> 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
> Can you term this example as an appropriate use of global statement?

No.

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

I'm bamboozled as to why anybody would want to do this. 'swap' can only 
exchange the values of 'x' and 'y' for the module in which all three are 
named, yuck.

> 
> Regards
> Manprit Singh
> 

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list