0

So I am learning the difference between global and local vars in Python 2.7 and as per my understanding

local var is one that is defined within a function and globar var is one that is defined outside of the function.

I created this simple function to test how these local and global vars work when used in combination

def f():
    global s
    print s
    s = "Python is great."
    print s 

Before I ran the function, I declared the global s

s = "I love python!" 
f()

The output was:

>>> f()
I love python
Python is great

I understand till this part, but what I don't understand is, when I call the run a print s outside the function, why is it printing the local variable instead of the global one. Does this mean that the global var s is used once and discarded?

>>> print s
Python is great

can someone please explain this?

pb_ng
  • 361
  • 1
  • 5
  • 19

2 Answers2

1

... what I don't understand is, when I call the run a print s outside the function, why is it printing the local variable instead of the global one.

There is no local s within the function. The global s statement causes the Python VM to use the s in the global scope even when binding it.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • So that means if I run a `print s` without declaring the global `s`, it will print the value of s as defined within the function, right? (since there is no global s defined?) – pb_ng Jun 30 '16 at 09:33
  • If you remove the `global s` statement within the function then calling the function will throw `UnboundLocalError` since the compiler will attempt to access the local `s` in the first line of the function (since you bound it within the function). – Ignacio Vazquez-Abrams Jun 30 '16 at 09:50
0

You declared s to be a global in the function, overriding the default behaviour, by using the global s statement. Because s is now a global, and you assigned a new value to it, that change is visible globally.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343