Python Variables

In this lesson, you will learn about variables in Python, what a variable is, how to declare, change the values to variables, and assign multiple values to multiple variables.


Variables in Python

A variable is a designated location in a memory where data is kept. Consider variables as a storage space for changeable data later in the program.


Declaring the Variables in Python

The interpreter allocates memory space and determines what can be placed in the reserved memory based on the data type of a variable. As you can see from the illustration given below, you can assign values to variables by using the assignment operator =.


Example

stdMarks = 90
print(stdMarks)

Output

90

Changing the Variables in Python

Because Python is a type-inferred language, the variable type does not need to be declared explicitly.

You can store these variables in Python as integers, decimals, or characters by giving them different data types. There is no special command to declare a variable in Python, and the instant you give a variable a value, it becomes a variable. As seen in the example below, variables can change their type after they are set and are not required to be declared with a certain type.

Example

stdMarks = 90
stdMarks ="John"
print(stdMarks)

Output

John

Here, a variable with the name stdMarks has been created. The variable has been given the value of 90.

stdMarks = 90
stdMarks ="John"

You can compare Variables to a container used to contain changeable clothes at any time. The value of the stdMarks was initially 90. In the second line, we updated it to “John”.

Note that with Python, we don’t give the values of the variables. Python instead assigns the variable a reference to the object(value).


Giving different values to different variables in Python

We can use this method to assign the same value to many variables simultaneously. Python enables you to assign the same value to many variables simultaneously.

Example

i = j = k = 100
print (i)
print (j)
print (k)

Output

100
100
100

Here, the three variables are allocated to the same memory location, creating an integer object with the value 100. Additionally, you can link several objects to various variables.

Example

i, j, k= 100, 2, "Hello World"
print (i)
print (j)
print (k)

Output

100
2
Hello World

Here, variables i and j are each given two integer objects with the values 100 and 2, while the string object ” Hello World” is given to variable k.

This concludes the Python Variables lesson. In the next lesson, you will learn different Constants in Python and their usage.