Reputation: 11
For the code below I have some doubt.
def spam():
global eggs
eggs = 'spam'
eggs ='global'
spam()
print(eggs)
The result is spam
.
My questions are as follows:
Do we have two global variables in that code?
Why it executes only eggs = 'spam'
but not eggs = 'global'
?
Thank you in advance.
Upvotes: 0
Views: 66
Reputation: 43
The result is spam because you ran the procedure after you assigned 'global' to eggs. The procedure assigns 'spam' to eggs.
Upvotes: 0
Reputation: 101
It does execute eggs = 'global'
, its value gets changed again by eggs = 'spam'
.
Your spam function accesses the global scope and changes eggs
to 'spam'
.
Upvotes: 1
Reputation: 77059
You only have one global variable, named eggs
in that code. You assign a value to it twice, first with the string 'global' and again with the string 'spam' in the function.
I think the term global
is a bit of a misnomer in Python. Names are only global to the module, so if you tried to access eggs
from another module, it would not exist unless you imported it.
Upvotes: 3