The fuel gauge on Mission Control's big screen keeps changing. Rocket has written the number on six sticky notes this morning, and each note is already out of date.
"I keep crossing numbers out," he says, holding up a crumpled pile. "There has to be a better way to keep track."
Raven looks at the pile and then at the gauge. "What do you notice?" she asks. "The label never changes. It always says fuel. Only the number beside it changes."
Nova projects a glowing label with an arrow pointing to a number. "I found a pattern," she says. "Give the value a name. When the value changes, the name just points to the new one."
Rocket sweeps the sticky notes into the recycling bin and opens the editor.
A variable is a name for a value. The line fuel = 100 makes a variable called fuel and stores 100 in it.
In Python, the = sign does not mean equals. It means store: work out the right side, then give that value the name on the left.
That is why fuel = fuel - 30 makes sense. Python takes the old value of fuel, subtracts 30, and stores the answer back in fuel.
# fuel.py
fuel = 100
print("Fuel:", fuel)
fuel = fuel - 30
print("Fuel:", fuel)
fuel = fuel - 25
print("Fuel:", fuel) Fuel: 100 Fuel: 70 Fuel: 45
Notice what print("Fuel:", fuel) does. It shows the text in quotes as written. For fuel without quotes, it shows the stored value.
| Name | Allowed in Python? |
|---|---|
| fuel_level | ? |
| 2nd_stage | ? |
| crew size | ? |
| stage2 | ? |
A variable holds whatever value it was given last. Changing one variable never changes another variable, even if it was made from the first one.
Programmers trace a program with a small table: one column for each variable, one row for each line.
# boxes.py a = 5 b = a + 2 a = 10 print(a, b)
| Line | a | b |
|---|---|---|
| a = 5 | 5 | (not made yet) |
| b = a + 2 | 5 | 7 |
| a = 10 | 10 | 7 |
| Statement | True or false? |
|---|---|
| In Python, = means store the value on the right in the name on the left. | ? |
| After b = a + 2, changing a also changes b. | ? |
| fuel = fuel - 10 is a mistake because fuel cannot equal fuel minus 10. | ? |
| A variable can be given a new value as many times as you like. | ? |
Variables let your programs remember. Tomorrow you will meet the four kinds of values Python uses most.