The basics of syntax

INPUT · Slides

Branching on a condition

01 / 06

Letting a program decide

Everything you have written so far ran every line, without exception, from the top.

From here you learn how to say "only when this is the case". The word for it is if, which means exactly what it does in English.

02 / 06

The shape of an if

It goes like this.

  • after if, write the condition
  • end the line with a :
  • on the next line, indented by four spaces, write what happens when the condition holds

The colon and the indent from the last lesson turn up straight away.

score = 80if score > 60:    print("pass")

Result

pass

03 / 06

When it does not hold, nothing happens

If the condition does not hold, the whole block is skipped. No error, just quiet — nothing appears.

So when nothing shows up, maybe your condition is not holding. It is a hard bug to spot precisely because nothing complains.

score = 40if score > 60:    print("pass")print("done")

Result

done

04 / 06

A block can be as long as you like

You can line up as many indented lines as you want. Lines indented by the same amount form one block.

If the condition holds they all run; if it does not, they are all skipped.

score = 80if score > 60:    print("pass")    print("well done")

Result

pass
well done

05 / 06

Telling inside from outside

The most important thing is reading which lines are inside the block and which are outside. The indent is your only clue.

In the example below, done has come back to the left margin, so it shows no matter what the condition says. Inside or outside changes everything.

score = 40if score > 60:    print("pass")print("done")

Result

done

06 / 06

An if can go inside an if

You can put another if inside the block of an if. When you do, you indent by another four.

The deeper it goes the harder it is to read, so two levels is about the limit. If you find yourself at three, see whether there is another way to write it.

score = 80if score > 60:    print("pass")    if score > 75:        print("and top marks too")

Result

pass
and top marks too