Global and local variable in Python

Python Variable:

               A variable is a container for storing data. It allows you to label and store data. Variables can store strings, numbers, lists or any other data type.

Example:

name = ‘Thomas’

name is the variable which stores the string data type.

When we write two values to the same variable, it overwrites the most recent value. For example

a = 10

a = 20

When you call a it will show 20, as it is the most recent value.

In Python Programming we will see two variables:

Global and local.

Global Variable:

               In Python, a variable which is created outside of the function is called global variable. It has scope throughout the program i.e., inside or outside the function. We can access both inside and outside of the program. It is often declared at the top of the program.

Trying to change value of Global variable inside a function:

Unbound local error is raised.

Local Variable:

               In Python, a variable inside a function is called local variable. It has scope only within the function in which is defined.

Accessing local variable outside scope:

Name error is raised.

Global Keyword:

               Global Keyword is used only when we want to change or modify the global variable outside its current scope. It is used to make change in gloabal variable in local context.

Syntax:

def f1( ):

global variable

The fundamental rules of the ‘global’ keyword are as follows:
  • When you create a variable inside the function, it is in a local context by default
  • When you create or define a variable outside the function, by default it is a global context, there’s no need for a global keyword here
  • Global keywords can be used to read or modify the global variable inside the function
  • Using a global keyword outside of the function has no use or makes no effect.
Using both Global and local variables:
Global and local variable with same name: