BCA / B.Tech 8 min read

Variables & Their Types

Variables & Their Types in Python:


In Python, variables are an important part of programming. A variable defines a location in memory to store any data. Variables in Python can be classified into two types: local and global. This classification is based on where and in which scope the variable is declared.

What are Variables?
We can understand variables as a place that is used to store specific data in the computer's memory. When we need that data in a program, we can access it by giving the variable's name.

Types of Variables:
1. Local Variable: A local variable is a variable that is defined inside a function or block. The scope of such variables is limited to only that function or block in which they are defined.
2. Global Variable: A global variable is a variable that is defined outside a function and can be accessed anywhere throughout the program.

Using the `global` Keyword:
If we need to change the value of a global variable inside a function, we have to use the `global` keyword.

Nested Functions and `nonlocal` Variables:
In Python, nested functions can be defined inside other functions. In such cases, we use the `nonlocal` keyword to refer to a variable that is neither local nor global.