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.
The basics of syntax
INPUT · Slides
01 / 06
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
It goes like this.
if, write the condition:The colon and the indent from the last lesson turn up straight away.
score = 80if score > 60: print("pass")Result
pass
03 / 06
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
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
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
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