Navya Gunda

Jun 19, 2021

1 min read

Scope of Global and Local variables

This blog is about global and local variables in python

Local variables can be accessed only inside the function where they are declared, but global variables can be accessed throughout the program body by all functions.

Let’s take an example of code :

def my_func():
var = 10
print("Value inside function:",var)

This is creating the function. The next code block is calling it.

var = 20
print("Value outside function:",var)

The value of var is equal to 20 . The function my_func() changed the value of var to 10, but it did not affect the value outside the function because var is a local variable which is inside the function is different from the one outside which is a global variable. Even though they have the same names, they are two different variables with different scopes.

To modify the value of variables outside the function, they must be declared as global variables using the keyword global.

def my_func():
global var
var = 10
print("Value inside function using global variable:",var)