Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How variable scope works in Python function?

In the following code

x = 141
def foo():
    x = 424 #local variable
    print(x)
foo()

the output is

424

How does the value of x change from 141 to 424?


1 Answer
Rajendra Dharmkar

A variable in Python is defined when we assign some value to it. We don’t declare it beforehand, like we do in C and other languages. We just start using it.

x = 141

Any variable we declare at the top level of a file or module is in global scope. We can access it inside functions.

A variable should have the narrowest scope it needs to do its job.

In given code

x = 141
def foo():
    x = 424 #local variable
    print x
foo()
print x

OUTPUT

424
141

Explanation:

When we assign the value 424 to x inside foo we actually declare a new local variable called x in the local scope of that function. That x has absolutely no relation to the x in global scope. When the function ends, that variable with the value of 424 does not exist anymore. So when the second print x statement is executed, the global value of x is printed.

If the global value of a variable is to be maintained in a local scope, the global keyword is used as follows in the code.

x = 141
def foo():
    global x
    x = 424
    print(x)
foo()
print(x)

OUTPUT

424
424
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.