Global and Local Variables in Python?



There are two types of variables: global variables and local variables. The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined.

Example

def func(): x = "Python" s = "test" print(x) print(s) s = "Tutorialspoint" print(s) func() print(x)

Output

In above program- x is a local variable whereas s is a global variable, we can access the local variable only within the function it is defined (func() above) and trying to call local variable outside its scope(func()) will through an Error as shown below −

Python
test
Tutorialspoint
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(x)
NameError: name 'x' is not defined

However, we can call global variable anywhere in the program including functions (func()) defined in the program.

Local variables

Local variables can only be reached within their scope(like func() above). Like in below program- there are two local variables – x and y.

Example

def sum(x,y): sum = x + y return sum print(sum(5, 10))

Output

The variables x and y will only work/used inside the function sum() and they don’t exist outside of the function. So trying to use local variable outside their scope, might through NameError. So obviously below line will not work.

File "main.py", line 2
   sum = x + y
   ^
IndentationError: expected an indented block

Global variables

A global variable can be used anywhere in the program as its scope is the entire program. Let’s understand global variable with a very simple example −

Example

z = 25 def func(): global z print(z) z=20 func() print(z)

Output

25
20

A calling func(), the global variable value is changed for the entire program. Below example shows a combination of local and global variables and function parameters −

def func(x, y): global a a = 45 x,y = y,x b = 33 b = 17 c = 100 print(a,b,x,y) a,b,x,y = 3,15,3,4 func(9,81) print (a)

Output

45 17 81 9
3

Advertisements