Storing Information in Variables
Give your data a name so you can reuse it
So far we've typed text directly into print. But often we want to remember a piece of information and use it again later. For that we use a variable.
A variable is just a name that points to a value. Think of it like a labelled box: you put something in the box, write a name on it, and later you can ask for whatever is in the box by its name.
Creating a variable
We create one with an equals sign:
name = "Sam"This reads as: "let the name name point to the text Sam." The = here doesn't mean "equals" like in maths "" it means "store this value under this name."
Now we can use name anywhere we like:
name = "Sam"
print(name)
print("Hello,", name)Notice we write name without quotes when we want its stored value. If we wrote print("name") with quotes, Python would just show the literal word name.
Variables can change
The value in a variable can be replaced at any time:
score = 10
print(score)
score = 25
print(score)That shows 10 then 25. The newest value wins.
Tip: Choose names that describe what they hold, like age, city, or total_price. Future-you will thank present-you. Names can't have spaces, so we often use underscores instead.
Your turn
Change the value of name to your own name and run the code.
Press “Run code” to see the result.
Quick check
Q1 What does the = sign do in age = 30 ?
Q2 If name = "Sam" , what does print("name") show?
Want to save your progress? It's free.
Create a free account