01 / 06
The basics of syntax
INPUT · Slides
The other road
02 / 06
The shape of an else
Where the if block finishes, come back to the left and write else:. Then indent again and write what goes inside.
You do not put a condition on an else. It means "everything that is left".
score = 40if score >= 60: print("pass")else: print("fail")Result
fail
03 / 06
Exactly one of them, always
if and else always run one and only one between them. Never both, never neither.
That is the big difference from writing two separate ifs. Nothing can slip through the gap.
score = 80if score >= 60: print("pass")else: print("fail")Result
pass
04 / 06
Watch where the else sits
else goes at the same depth as its if. Indent it and you get a SyntaxError.
The inside of the if moves right; the else does not. That step is what marks the end of the block.
score = 40if score >= 60: print("pass")else: print("fail")print("marking done")Result
fail marking done
05 / 06
No condition on an else
A common slip: writing something like else score < 60:. That is an error.
else takes on everything that is left, so there is nowhere for a condition to go. If you want one, you want the elif from the next lesson.
06 / 06
Sometimes you do not need one
If the answer to "and otherwise?" is "nothing", leave the else out. An empty else only makes things harder to read.
Write one when both roads mean something. Only writing what you need is what tidy code is.
price = 3000if price >= 2000: print("free postage")Result
free postage