What are variables in a programming language?

What is a variable in Programming languages?

A variable is a name you give to a computer memory location so that the name can represent the value stored in that memory location.

You can also say that – A Variable is like a container named by you where you can store a value, and with the help of the container name you can access the value that the container holds.

Example: a = 10 – where a is the variable name 10 is the value of the variable.

How variables and their values stored in the RAM?

How variables and their values stored in the RAM
How variables and their values stored in the RAM?

Use of the variables

Variables are used to store values or data.

Why do we use variables to store values?

Suppose you write a code where you add 2 with 3, 5, 9, and 12.

print(2+3)
print(2+5)
print(2+9)
print(2+12)

What is the print() in the above code?print() is a function of Python language which is used to display the result on the screen.

Now for some reason you change your mind and you want to add those numbers with the 3 instead of 2.

Now your code will look like the following –

print(3+3)
print(3+5)
print(3+9)
print(3+12)
🤔 Problem:

The problem is that you had to replace 2 with 3 in all the places.

Let’s say you have thousand lines of code, and you want to do this kind of thing, then there is a very high chance of mistake.

✔️ Solution:

Use the variables.

a = 2
print(a+3)
print(a+5)
print(a+9)
print(a+12)

Now I want to add with 3, so I assign 3 to the variable a. The code is almost the same as above, only one place has been changed a = 3.

a = 3
print(a+3)
print(a+5)
print(a+9)
print(a+12)

Another benefit of variables

You can change the value of a variable programmatically at the run time.

Easy example:
a = 5
b = 2
a = a + b
print(a)
7
Slightly complicated example:

If you know about conditional statements, then this is a very simple example.

a = 3

may_i_change = False # No
if(may_i_change):
    a = 5

# a = 3
print(a+9)
12
a = 3

may_i_change = True # Yes
if(may_i_change):
    a = 5

# Now a = 5
print(a+9)
14