Google News
logo
Variables
Python variables are the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. An assignment statement creates new variables and gives them values.

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.

Following examples of python variables : 

>>> name = 'Free Time Learning'
>>> x = 120
>>> value = 91.125784037

The first assigns a string to a first variable - name; the second assigns the integer 120 to x; the third assigns the (approximate) value is 91.125784037.

To display the value of a variable, we can use a print statement :

>>> print(name)
Free Time Learning
>>> print(x)
120
>>> print(value)
91.125784037
The type of a variable is the type of the value it refers to
>>> type(name)
<class 'str'>
>>> type(x)
<class 'int'>
>>> type(value)
<class 'float'>
Multiple Assignment :

Multiple assignment can be done in Python at a time. There are two ways to assign values in Python :

1. Assigning single value to multiple variables :

>>> x=y=z=50
>>> print(x)
50
>>> print(y)
50
>>> print(z)
50

2. Assigning multiple value to multiple variables :

>>> x,y,z = 25,63,90
>>> print(x)
25
>>> print(y)
63
>>> print(z)
90
Swap variables :

Python swap values in a single line and this applies to all objects in python :

>>> x = 25
>>> y = 72
>>> print(x)
25
>>> print(y)
72
>>> x, y = y, x
>>> print(x)
72
>>> print(y)
25