Global and Local variables

Global variables are those which can be use in global space i.e,  accessible to any functions in a particular file or class. But local variables are limited to scope of a function only. They lost their value after coming out of function.

Let’s see how to create global variable and local variables and how to use them.

In [1]:

## Creating a global variable
a = "Hello! Welcome to python tutorials."

 

def func():

## It will automatically takes the value of global variable as we didn’t define any other local variable “a” inside fubction.
print(a)

In [2]:

## Calling the function toc check what value of "a" will it print.

 

func()

Hello! Welcome to python tutorials.

In [3]:

## Creating a global variable
a = "Hello! Welcome to python tutorials."

 

## Define function which is creating another local variable “a” and without modifying global vriable value.

def func():

## It is another local variable of function func()
a = “Hello! Everyone”
print(a)

In [4]:

func()

 

## Here it will print the value of global variable “a” which is not not changed even if the a’s value
## in function func() is changed because func() is not accessing the global variable and then chnaging it.
## It is actually creating another local variable.
print(a)

Hello! Everyone
Hello! Welcome to python tutorials.

In [5]:

a = "Hello! Welcome to python tutorials."

 

def func():
## Now by using “global” keyword we are actually modifying the global variable a instead of creating a new local variable.

global a
## assigning a new value
a = “Hello!”
print(a)

In [6]:

func()

 

## Here it will print the global variable a’s value but with modified one.
print(a)

Hello!
'Hello!'

Hope you understood the concepts of local and global variables. There are many cases when local and global comes into picture. So, it is important to keep this concept in mind.

Stay tuned! Keep Learning with us.