The basics of syntax

INPUT · Slides

Why bother with variables

01 / 06

Writing the same value over and over hurts

Suppose a program uses a tax rate in three places, with the value written straight in.

print(100 * 1.1)print(200 * 1.1)print(300 * 1.1)

It runs. But when the tax rate changes you have to fix all three. Miss one and that line quietly keeps using the old rate.

02 / 06

Give it a name and there is one place to fix

The same thing with a variable looks like this. There is exactly one line to change.

What matters is that forgetting is no longer possible. People slip up, always, so you shape things so that slipping up cannot happen.

tax_rate = 1.1print(100 * tax_rate)print(200 * tax_rate)

Result

110.00000000000001
220.00000000000003

03 / 06

The name is the explanation

The other job a variable does is explaining.

print(1000 - 430) tells you nothing about what is being worked out. Written like this, you know just by reading. Not needing a comment at all is the best place to be.

paid = 1000price = 430print(paid - price)

Result

570

04 / 06

Name the steps along the way

A long sum reads better if you break it up and name the pieces.

print((150 * 3 + 220 * 2) * 1.1)

Split like the code below and you can see where each thing is worked out.

bread_total = 150 * 3milk_total = 220 * 2print(bread_total + milk_total)

Result

890

05 / 06

A variable can be built from a variable

You can use what is inside one variable to make another.

The right-hand side is worked out first, and the result goes into the name on the left. That lets you lay the working out from the top down.

unit_price = 200count = 3total = unit_price * countprint(total)

Result

600

06 / 06

You can go too far, too

That said, not everything deserves a name. Forcing a name onto a value you use once can make things harder to read, not easier.

Two rough tests.

  • A value that appears twice or more gets a name
  • A value whose meaning is unclear gets a name

If you cannot decide, name it. Having too many names is a smaller problem than having none and being lost.