The very first approach towards understanding a programming language is to know about variables and how they are declared, initialized as well as used. After reading this article, you will able to understand python variables, why we need variables in python, various approach to create variables name (declare variables in python), assigning value to variables in python and how to use a python variable in the program. Find below the topics elaborated in this article. You can navigate to a particular topic by clicking on them. Video link of Python variables is embedded with this article.
Table of Contents
- Introduction to python variables
- Need for variables in Python
- Value assignment to a variable
- Python Variables memory references
- Variable object Identity
- Variable naming convention in Python
- The data type of Python variables
- Reserve keyword in Python
- Deleting Python Variables
Introduction to python variables
Python variables are the temporary location name to store values. Variable can store various data types such as number, string, boolean or complex value. Variables are the essential part of any program so is the case with Python. It stores a value which can be used by several sections of the program or during calculations. This value is stored at a specific location in the memory.
Variables in Python can be understood with a real-world scenario, for example, a basket is required to store the Apples. In this example, the basket acts as a location address and apple act as a value/object.
Need for variables in Python
As we have seen in the introduction part, variable store a value which can be used during the calculation, assigning value to another variable or by some function. Python variables can also be used to initialize, hold, pass or update values. Without a variable, it is impossible to write any code or script in python (in fact in any language). Since python is a dynamically typed language, it does not require to declare the data type of a variable in advance. In General, most of the programming language supports static type variable declaration. In a statically typed language, the data type must be declared and placed before the variable name and this variable carry the same data type throughout its lifetime in that particular program.
Video on variables in Python @ aipython YouTube
Value assignment to a variable
As we have just learned in the previous section, that python is dynamically typed language. Any Value can be assigned to a variable using an assignment operator. The syntax for value assignment to a python variable is –
Syntax: variable name = value
x = 10
y = "aipython"
z = 2+3j
The value on the right side of the operator (which is equal to sign) is being applied to the name present on the left side. When a value is assigned to a variable, it takes the data type accordingly and the datatype changes, when a different type of value is assigned.
At any point in time, we can check the data type of a particular variable using type () method. The syntax for type method on variable taken from the previous example is shown below.
Assigning a single value to multiple variables
In the previous example, we have seen how to declare and assign the value to a python variable. In this section, we are going to see how one value can be assigned to a set of variables in one line of python code.
a=b=c = 10
Assigning distinct values to many variables
Similar to assigning one value to multiple variables, we can also assign distinct value to many different variables using one line of python code.
x, y, z = 5, "aipython", True
In the above example, all variables are holding the value of different type hence data type of each variable will be accordingly and the same can be checked using type () method.
Python Variables memory references
When a variable is declared and initialized in python, it will allocate memory and hold the value. This memory (along with the value) will be referenced by a variable name. Python variable is a symbolic name which is referencing to a memory.
This is a sample memory block used by Python.
Let us understand by looking at the pictorial example,
After executing the following code in python,
x = 20
y = 50
Two objects are created in memory which is holding the individual value.
Now suppose another variable ‘p’ is created with the same value as of ‘x’, this will not create a new memory instead it will reference the memory of x with one more pointer named ‘p’.
p = 20
When the below statement is executed,
x = y
In the end, when both variables (x & p) are deleted using the python program then this memory is no more referenced (by either x or p) and at the same time, no value exists in that memory. At this point of time, the only variable y is referenced to a memory holding the value of 50.
Variable object Identity
In python, every object that is created is given a unique identity and no two objects can have the same identity. A variable (or object) holds a particular identity throughout its lifespan. After the variable is deleted then only this identity can be taken by another object. Identity of any variable can be found using the method id(variable_name).
x = 20
140706629251360 # this value can be different on your system.
After deleting the variable identity is lost and the program will produce an error (‘x’ is not defined).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
Variable naming convention in Python
We have seen in the preceding section, it is easy to declare a variable and assign a value to it. Naming a python variable does not require any expertise still, there are certain rules (or guidelines) issued by Python software foundation towards naming a python variable. Practically, there is no length limit imposed for naming a variable.
Allowed naming conventions are –
- Any letters can be used for naming a variable (e.g. –> a, ab, abc, x, xy, xyz)
- Underscore ( _ ) can also be attached (before/after/in the middle) with letters for writing variable name (e.g.-> _xy , x_y, xy_)
- Only alpha-numeric value along with underscore can be used to create a variable name.
- Python is case sensitive, which means any word or letter written in upper & lower case will be treated as a different value. For example, Name & name are different for python.
Not Allowed naming conventions are –
- Variable name can not start with numbers (e.g. -> 0_a, 1_test )
- White spaces (blanks) can not be present in the variable name (e.g. -> a b, my variable). The most common practice is to fill the gap with an underscore character.
- Special sign/symbol (“+” and “-“) can not be used in variable name (e.g. -> a+b , x-y )
- Python Reserve keyword can not be used for naming a variable.
The data type of Python variables
As soon as a variable is declared with some value, the data type is assigned to it. There are a variety of data types supported by python. Check out the comprehensive tutorial on Python data types. The data type of a variable purely depends on how the variable is used in the program. Normally, a variable holds a specific data type throughout the lifetime until and unless it is required to change because of certain calculation.
Let us see via an example,
a = 10
b = 3
c = 0
# Variable a, b, c have same data type, which is 'int'
c = a/b
c = 3.333
<class 'float'> # Now the data type of variable c changes after calculation.
Reserve keyword in Python
Python does not permit the use of some words for naming the variable. These words are reserved by python programming language hence known as Reserved Keywords. Complete list of python reserved keywords is given below.
false, def, if, raise, None, del, import, return, True, elif, in, try, and, else, is, while, as, except, lambda, with, assert, finally, nonlocal, yield, break, for, not, class, from, or, continue, global, pass.
Deleting Python Variables
In Python, a declared variable can be deleted at any time using a del keyword. Once the variable is deleted it can not be used further in the program.
Keep Learning and Keep Growing !!