The basics of syntax

INPUT · Slides

The shorter way to write it

01 / 06

Writing the same name twice is a chore

Lines like total = total + 120, where the same name appears twice, turn up constantly. Long names make that tiring to type, and mistyping one of the two is easy to do.

So Python gives you a shorter way.

02 / 06

+= adds and puts it back

x = x + 1 can be written x += 1. They mean exactly the same thing.

Read it as "add 1 to x". The name only appears once, so there is less to get wrong.

number = 10number += 1print(number)

Result

11

03 / 06

Take away, times and divide work the same

Every symbol has one of these. You just put an = after it.

  • x -= 3x = x - 3
  • x *= 2x = x * 2
  • x /= 4x = x / 4
  • x //= 4x = x // 4
  • x %= 3x = x % 3
score = 100score -= 30score *= 2print(score)

Result

140

04 / 06

It is -= , not =-

Watch the order. Symbol first, = after.

x =- 3 is not an error, but it is read as x = -3. Instead of "take 3 away" you get "put minus 3 in". It slips through precisely because nothing complains.

x = 10x -= 3print(x)

Result

7

05 / 06

It works on text too

+= works on text as well, where it means stick this on the end.

Handy when you are assembling a piece of text a bit at a time.

text = "a"text += "b"text += "c"print(text)

Result

abc

06 / 06

When to use it

The short form only works when you are updating the same variable. You cannot use it for total = unit_price * count, where the value comes from elsewhere.

Either way runs, but the short form says "this is an update" at a glance, so use it when it is one. In real Python code you will see it far more often than the long form.

total = 0total += 120total += 80print(total)

Result

200