Variables: Boxes That Hold Values

What is a variable?

A variable is a name that holds a value, so you can use that value later.

Think of it like this: A variable is like a labelled box. You write name on the box and put "Asha" inside. Whenever you need it, you look in the box called name.

Creating a variable

Write the name, an equals sign =, and the value:

name = "Asha"
age = 21
print(name)
print(age)

Output

Asha
21

In Python, = does not mean “is equal to” like in maths. It means “store this value in this box”. We call this assigning a value.

Using variables together

city = "Pune"
temperature = 31
print("It is", temperature, "degrees in", city)

Output

It is 31 degrees in Pune

Changing a variable

A variable can be given a new value at any time. The old value is thrown away:

score = 10
print(score)
score = 25
print(score)

Output

10
25

You can even use the old value to make the new one. Python works out the right side first, then stores the answer:

coins = 5
coins = coins + 3
print(coins)

Output

8

Naming rules

AllowedNot allowedWhy
user_nameuser nameNo spaces – use an underscore _
score22scoreA name can't start with a number
totaltotal$Only letters, numbers and _
my_classclassPython's own keywords are reserved

Names are case-sensitive: Age and age are two different variables.

Tip: Pick names that say what is inside: price is much clearer than p or x. Python programmers write longer names in snake_case, like total_price.

HOME LEARN COMMUNITY DASHBOARD