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

Mats Wichmann mats at wichmann.us
Tue Sep 29 12:03:20 EDT 2020


On 9/28/20 8:49 PM, 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

So to sum up:

that is how global works. when you assign a value to a name, the name is
created in the current scope.  inside a function, that scope is the
function's local scope. when you use the global statement, you tell it
not to create it in the current scope, but in the global scope - and if
the name already exists in the global scope, it uses that one.

but as presented, this isn't necessarily a *good* use of the facility.



More information about the Tutor mailing list