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
>>> type(name) <class 'str'> >>> type(x) <class 'int'> >>> type(value) <class 'float'>
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
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