Variables, explained simply
A variable is like a labelled box. You pick a name for the label, and put a value inside. Later, whenever you use the name, Python looks inside the box and uses whatever is there.
You create a variable with a single equals sign: lamps = 3. In Python the equals sign means "store this", not "is the same as". You can put a new value in the box at any time, and the old one is replaced.
Variables can do maths too. If you write lamps = lamps + 1, Python reads the current value, adds one, and stores the answer back in the same box.
Example: A counter that changes
lamps = 3
print(lamps)
lamps = lamps + 2
print(lamps)Output
3
5Try this
- Make a variable called age, store your age, and print it.
- Store the number of pencils you own, give two away in code, and print what is left.
- Try using a variable before you create it. What does Python say?
