Variables in Python

Variables: Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.

In python, variables are dynamic and loosely type. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.

For example: If you want to create a variable A and you store 5 in it. As we know 5 is an integer. So, variable A datatype will be also integer.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> A = 3 #Variable A has been create and an integer value has been assigned to it.
>>> print(A)
>>> print(type(A)) # type() is a function. When you pass variable name as argument than it will return the type of variable.
<class 'int'>
>>> print(id(A)) # id() is a function. When you pass variable name as argument than it will return the location of the variable
>>> print(hex(id(A))) # Conversion of location to hex decimal to locate it on memory.

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example: a = b = c = 1
Here, an integer object is created with the value 1, and all the three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example: a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one string object with the value "john" is assigned to the variable c.