Local and Global variables in Python

Local Variables

When you declare variables inside a function , they are not related in any manner to outside the function(i.e the main block) This is called as Scope of the variables.Every variable inside your program have a Scope associated with it. In simple Words Scope of a variable means the area in which we can use the variable or access the variable

x = 200


def func(x):
    print('x is', x) # now we refer to x outside the function
    x = 5           # now here we declare a x variable for that function 
    print('Changed local x to', x)


func(x)
print('x is still', x)

Output

x is 200
Changed local x to 5
x is still 200

How It Works

The first time we use the print statement then Python first searches in the function block itself(Local Scope)but Python does not find any Variable name x.Then Python seaches in the main block itself and found the variable and Print it’s value.

The second print statement python again search in the main block and find a variable name x (because we declare a variable before calling the print statement) It prints the value of x

The third print statement is outside the function and so that’s why python print the value of x variable in main block.

The global statement

If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement.

You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged it should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is.

x = 200


def func():
    global x

    print('x is', x)
    x = 5
    print('Changed global x to', x)


func()
print('Value of x is', x)

Output

x is 200
Changed global x to 5
Value of x is 5

How It Works

The global statement is used to declare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected in the value of x in the main block.

You can specify more than one global variable using the same global statement e.g.

global x, y, z.