Computer >> Computer tutorials >  >> Programming >> Python

How variable scope works in Python function?


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.

Example

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.

Example

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

Output

424
424