Skip to main content
Practice

Containers for Data, Variables

In programming, a variable is like a container that holds data.

Just like we store important data on a USB drive or in the cloud in our daily lives, we use variables in programming to store data or values.

A variable is a storage space in the computer where data is saved for later use. It allows us to store a specific value and retrieve it whenever needed.

Note: The space in the computer where the value of a variable is stored is called Memory. A variable references the value stored in the memory.


Declaring a Variable = Preparing a Container

In programming, declaring a variable is like preparing a new container to hold data.

By declaring a variable, we give a name to the data-holding container, allowing us to retrieve the data inside the container using its name whenever needed.

For example, the Python code below declares a data container (variable) named age and does not put any value in it.

Python Variable Declaration
age = None

age is the name of the variable, and in Python, None means "nothing is put inside yet."

In Python, you don’t need to follow complex syntax; simply defining the name of the variable is sufficient.


Assigning a Value to a Variable = Putting an Item in the Container

Assigning a value to a variable is like putting an item in the prepared container.

When assigning a value to a variable, we use the = symbol.

Unlike in general mathematics, in programming, = means assigning the value on the right to the variable on the left.

For example, the code below assigns the value 10 on the right to the variable age on the left.

Assigning a Value to a Variable
age = 10

The variable age now holds the number 10.

This value can be used to represent that some entity is 10 years old.

With the declared variable age, we can retrieve this number anytime using its name.

Using Variable Value
new_age = age + 5  # 10 + 5 = 15

print(new_age) # Prints 15

In the code above, the variable new_age holds the value 15, which is 5 added to the value stored in the age variable.

Also, we can use print(age) to display the value stored in the age variable on the screen.

Note: In Python, the = symbol is called the assignment operator. To compare if two values are the same, use ==.


Reassigning a Variable = Putting a New Item in the Container

Just as the item inside a container can be replaced, the value held by a variable can also be changed at any time.

For example, if you assign 10 to age and then reassign 20 to it, age will hold 20.

Variable Reassignment
age = 10  # Assign 10 to age
age = 20 # Reassign 20 to age

print(age) # Prints 20

The 10 that was previously stored is no longer held by the age variable.


In this way, a variable allows you to store a specific value and change it whenever needed, aiding in flexible data handling in a program.