Variables
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A box with a name
- A variable is a named box that holds a value.
- You put a value in the box, then use the name later.
- The value can be a number or a string.
Make a variable
- Write
name = valueto store a value. - The name is on the left. The value is on the right.
=means "store this value", not "is equal to".
city = "Paris"
print(city)
Naming rules
- Use letters, digits, and the underscore
_. - A name cannot start with a digit and cannot have spaces.
- Names are case-sensitive:
scoreandScoreare different. - Pick clear names like
ageortotal_score.
Change a variable
- You can store a new value at any time.
- The new value replaces the old one.
- The name still points to one value — the latest one.
count = 1
count = 2
print(count)
Constants
- A constant is a value that should not change.
- Python has no special keyword for it.
- By convention, we write constant names in
UPPERCASE.
PI = 3.14159
print(PI)
Now you try
- Use a variable for each task below.
- Press Check answer to test your code.
Create a variable called age and store the number 15 in it.
Click Run to see the output here.
The variable color starts as "red". Reassign it so that it becomes "blue".
Click Run to see the output here.
Constants are written in UPPERCASE by convention. Create a constant MAX_SCORE and set it to 100.
Click Run to see the output here.