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
| Allowed | Not allowed | Why |
|---|---|---|
user_name | user name | No spaces – use an underscore _ |
score2 | 2score | A name can't start with a number |
total | total$ | Only letters, numbers and _ |
my_class | class | Python's own keywords are reserved |
Names are case-sensitive: Age and age are two different variables.
Tip: Pick names that say what is inside:
priceis much clearer thanporx. Python programmers write longer names insnake_case, liketotal_price.