The basics of syntax

INPUT · Slides

The order things happen in

01 / 06

Times and divide go first

Just like in maths, *** and / happen before + and -**.

So 2 + 3 * 4 is not "add 3 to 2 then times by 4". It is "times 3 by 4, then add 2".

print(2 + 3 * 4)

Result

14

02 / 06

Brackets jump the queue

To change the order, wrap it in ( ). Whatever is inside is worked out first.

Brackets for grouping a sum look exactly like the brackets of print. When they nest, stay calm and read from the inside out.

print((2 + 3) * 4)

Result

20

03 / 06

Equal strength means left to right

When symbols of the same strength sit side by side, like + and -, they go from the left.

100 - 30 - 20 means (100 - 30) - 20, so 50. It is not 100 - (30 - 20), which would be 90.

print(100 - 30 - 20)

Result

50

04 / 06

To the power of is **

(two asterisks) raises a number to a power. 2 10 is 2 multiplied by itself 10 times.

It is not the same as the * for times. One asterisk or two changes the meaning completely, so watch your typing.

print(2 ** 10)

Result

1024

05 / 06

Powers are the strongest

** happens even before * and /. The pecking order goes like this.

  • first of all … ( )
  • then … **
  • then … * / // %
  • last … + -
print(2 * 3 ** 2)

Result

18

06 / 06

When in doubt, add brackets

Knowing the order matters, but if you are not sure, just put the brackets in.

Extra brackets change nothing about how it runs, and they make your intent plain to whoever reads it. The thing that matters most is that you can read it back later.

print(2 + (3 * 4))

Result

14