In this Python tutorial, we will learn what variables are, how to declare a variable, how to assign values to variables, and how to read the values from variables.

Python – Variables

In Python, variables are the means through which we can access values stored in memory. And as a matter of fact, in any programming language, variables act as containers to hold values.

Assign Values to Variables

Assignment Operator = can be used to assign values to variables. Variable must be the left operand and the value assigned to it must be right operand. An example to assign a variable a with value 100 is given in the following.

</>
Copy
a = 100

There is no explicit declaration required for a variable in Python, unlike in many other programming languages. When a variable is used in the python code, python interpreter automatically interprets the data type from the value assigned to the variable.

Reading Values from Variables

To read the value stored in a variable, the variable has to be given on the righthand side of the assignment operator, or in an expression, etc.

In the following example, we take two variables a and b and assign them with integer values. We try to add the values stored in these two variables. We read the values from variables by including them in an expression, which in this case is a + b.

While Python interprets this code, a and b are substituted with the values stored in them.

Example.py

</>
Copy
a = 10
b = 20
total = a + b
print(total)

Output

30

Assigning Multiple Variables in a Single Line

In Python, we can assign multiple variables a value in a single statement.

In the following program, we take variables for months and assign values of 31 for months with 31 days, 30 for months with 30 days, and 28 for feb. We assign all the months with 31 days in a single statement. Similarly for months with 30 days.

Example.py

</>
Copy
jan = mar = may = jul = aug = oct = dec = 31
apr = jun = sep = nov = 30
feb = 28
total = jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec
print(total)

Output

365

Conclusion

In this Python Tutorial, we learned about Variables in Python: how to assign values to them and read values from them, with examples.