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

Manprit Singh manpritsinghece at gmail.com
Mon Sep 28 22:49:45 EDT 2020


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?
Here x & y should not be used before their global statements nor should
they appear as formal parameters  in function definition.

Regards
Manprit Singh


More information about the Tutor mailing list