A variable is a name for a value
Programs compute in steps, and a step is useless if the next line cannot reach its result. Variables exist so a result can be kept and reused: a game keeps a score, a shop keeps a running total, a loop keeps its place. Without them, nothing in a program could accumulate or change over time.
A variable gives a value a name so you can use it later. The = sign means assign: take the value on the right, attach the name on the left.
score = 10Now the name score refers to the value 10. Use the name anywhere you would use the value. Assigning again replaces what the name points to:
score = 10 score = score + 5 # compute 10 + 5, then point score at the result
Naming rules: letters, digits, and underscores, and a name cannot start with a digit. By convention Python names are lowercase with underscores, like total_price.
A comment starts with #. Python ignores everything after it on that line. Comments explain why code exists, for the humans reading it.
Code exercise · python
Run this. Watch the variable change between the two prints, and note that the comment line produces no output.
Code exercise · python
One more, a rule that bites beginners: an assignment copies the value once, at the moment it runs. It does not create a live link. `total` was computed while `price` was 40, so changing `price` afterwards does not recompute `total`.
Quiz
After running `x = 4` then `x = x * 2` then `x = x + 1`, what is x?
Code exercise · python
Your turn. Create a variable `steps` with value `8000`. Add `2500` to it using the variable itself (like `score = score + 5` above). Then print `Steps today:` followed by the value, using one print with a comma.