[Tutor] Just need to check a basic understanding of global statement
alexkleider
alexkleider at protonmail.com
Tue Sep 29 10:43:24 EDT 2020
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Monday, September 28, 2020 7:49 PM, Manprit Singh <manpritsinghece at gmail.com> 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?
> Here x & y should not be used before their global statements nor should
> they appear as formal parameters in function definition.
>
> Regards
> Manprit Singh
>
Rather than using a function, what about simply: x, y = y, x
as in
(p37) alex at X1:~$ python
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'hello'
>>> y = 'hi'
>>> x
'hello'
>>> y
'hi'
>>> x, y = y, x
>>> x
'hi'
>>> y
'hello'
>>>
More information about the Tutor
mailing list