What is a variable in Python?
How Can We Help?
Teacher,
Cat enthusiast
- The 2022 End of Year Website Update - 01/01/2023
- Celebrating Ada Lovelace day - 10/10/2022
- Website update 5/9/22 - 05/09/2022
A variable is a storage location for data.
Say a user entered their name into our program. We would want our program to remember the users name so that we could talk to them on a personal level.
This is exactly what a variable is for, storing data in our programs.
For example:
name = "Dave"
print(name)
In this example we have stored the name “Dave” in a variable called name. Now whenever we want to access this data (the word “Dave”) all we do is call the variable name.
It’s handy to think of variables like a box. We store the data inside the box and put a label onto the box so we know what is inside it.
In Python, variables can store any type of data so text (strings), or numbers (integers)
Variables can vary
The last important point about variables is that they can be varied (the clue is in the name!).
If we had a game where we stored the health of a player in a variable called health, things might happen to our player for him to lose health so we would need to update the value stored in our health variable.
For example:
health = 100
monster_attack = 10
health = health - monster_attack
print(health)
In the example above, our variable health starts at 100. When a monster attacks our player it reduces the value by 10 points so the value now stored in our health variable is 90.