Global and Local Variables in Python?

PythonServer Side ProgrammingProgramming

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.

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

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. 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.

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

Output

15

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.

print(x)

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 -

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,b,x,y)

Output

45 17 81 9
45 15 3 4
raja
Published on 30-Apr-2019 16:07:07
Advertisements