In this article, we will discuss the different aspects of using variables in Python like declaring variables, assigning values to variables and the data types of variables.

Declaring Variables in Python

In Python, there is no need to explicitly declare variables. Instead we just assign a value to a variable and start using it in expressions. The below code will assign the integer value 10 to variable a and the integer value 15 to variable b.

#declaring and using variables
a=10
b=15
print(a)
print(b)

Variable Data Type in Python

The type of a variable in Python is decided at runtime depending on the current value of the variable. In the below code, the variable a is of type ‘int‘, the variable b is of type ‘float‘ and the variable c is of type ‘complex‘.

#understanding variable type
a=10          #int
print(type(a))
b=2.5         #float
print(type(b))
c=5+6j        #complex
print(type(c))

Moving further, the same variable may have different type at different points in the program. As an example, see the below code. The variable a is of type ‘int‘ at line number 1 and the type changes to ‘float‘ at line number 3.

#same variable, different types
a=10          #int
print(type(a))
a=2.5         #float
print(type(a))

Assigning Values to Variables in Python

Assign constant values and expressions to variables

Values can be assigned to variables in Python using the assignment operator ‘=’. The value evaluated by the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.

a=10      #a is equal to 10
b=a+5     #b is equal to 15
c=a*10    #c is equal to 100

Assign same value to multiple variables

Python provides an easier way to assign the same value to multiple variables as shown in the below code.

a=10
b=10
c=10
#A better way to assign in Python
a=b=c=10

Assign multiple values to multiple variables

Python provides an easier way to assign multiple values to multiple variables as shown in the below code.

a=10
b=20
c=30
#A better way to assign in Python
a,b,c=10,20,30
Last modified: March 27, 2023

Author