difference between local and global variable in python

The Difference Between Local and Global Variables in Python

In Python, variables are used to store data values that can be accessed and manipulated throughout your code. When declaring variables, there are two types that you need to take note of: local and global variables.

Local Variables

Local variables are those that are declared inside a function or block of code. They are limited in scope to the function or block they are declared in and cannot be accessed outside of it. In other words, these variables only exist within the scope of the function that they are declared in.

For example, let’s say you have a function that calculates the area of a rectangle:

“`python
def calculate_area(length, width):
area = length * width
return area
“`

In this function, `length` and `width` are parameters of the function, and `area` is a local variable that is defined within the function. The value of `area` can only be accessed within the function and cannot be accessed outside of it.

See also  difference between laptop and desktop

Global Variables

Global variables are those that are declared outside of any function or block of code. They have a global scope and can be accessed and manipulated from anywhere within your code.

For example:

“`python
pi = 3.14

def calculate_area(radius):
area = pi * (radius ** 2)
return area
“`

In this code snippet, `pi` is a global variable that is defined outside of the function. Within the `calculate_area` function, `pi` is used to calculate the area of a circle. Because `pi` is a global variable, it can be accessed and used within the function.

Summary

In summary, local variables are limited in scope to the function or block of code they are declared in, while global variables have a global scope and can be accessed from anywhere within your code. Understanding the difference between these two types is essential for writing clean, efficient and well-structured code in Python.

Table difference between local and global variable in python

Local Variable Global Variable
A local variable is defined inside a function and is only accessible within that function. A global variable is defined outside of any function and is accessible throughout the code.
The lifespan of a local variable is only as long as the function in which it is defined. The lifespan of a global variable is for the entire duration of the program.
A local variable can have the same name as a global variable, but they are completely separate variables. Global variables can be accessed and modified from anywhere in the program.
Local variables are used to store temporary data within a function. Global variables are used to store data that needs to be accessed by multiple functions or throughout the entire program.