What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.
Python Variable Types
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like a, aa, abc, etc.
How to Declare and use a Variable
Let see an example. We will define the variable in Python and declare it as “a” and print it.
a=100
print (a)
Re-declare a Variable
You can re-declare Python variables even after you have declared once.
Here we have Python declare variable initialized to f=0.
Later, we re-assign the variable f to value “Welcome FutureCode"
Python 2 Example
Python 3 Example
Python Variable Types: Local & Global
There are two types of variables in Python, Global variable and Local variable. When you want to use the same variable for the rest of your program or module you declare it as a global variable, while if you want to use the variable in a specific function or method, you use a local variable while Python variable declaration.
Let’s understand these Python variable types with the difference between local and global variables in the below program.
- Let us define a variable in Python where the variable “f” is global in scope and is assigned value 101 which is printed in the output
- Variable f is again declared in function and assumes local scope. It is assigned the value “I am learning Python.” which is printed out as an output. This Python declare a variable is different from the global variable “f” defined earlier
- Once the function call is over, the local variable f is destroyed. At line 12, when we again, print the value of “f” is it displays the value of global variable f=101
Python 2 Example
Python 3 Example
While Python variable declaration uses the keyword global, you can reference the global variable inside a function.
- Variable “f” is global in scope and is assigned value 101 which is printed in the output
- Variable f is declared using the keyword global. This is NOT a local variable, but the same global variable declared earlier. Hence when we print its value, the output is 101
- We changed the value of “f” inside the function. Once the function call is over, the changed value of the variable “f” persists. At line 12, when we again, print the value of “f” is it displays the value “changing global variable”
Python 2 Example
Python 3 Example
You can also delete Python variables using the command del “variable name”.
In the below example of Python delete variable, we deleted variable f, and when we proceed to print it, we get the error “variable name is not defined” which means you have deleted the variable.
Example of Python delete variable or Python clear variable :
Comments
Post a Comment