Coding for All
Lesson 11: Elif
Elif Check several conditions, one after another.
1number = 2
2if number == 1:
3 print("one")
4elif number == 2:
5 print("two")
6else:
7 print("something else")
Terminal
$ python3 main.py
two
Every line, explained
number = 2
This creates a variable: a named box that stores a value. In Python you just write name = value: the = stores the value on the right into the name on the left. No special type word, no semicolon; Python keeps it simple.
if number == 1:
if checks the condition after it. Two things to notice: the line ends with a colon :, and the lines that belong to the if are indented 4 spaces underneath. Python uses indentation to know exactly which code is "inside" the if. If the condition is True the indented code runs; otherwise Python skips it. (The editor indents for you here; in a real editor you would type the 4 spaces.) == asks "are these equal?". Careful: a single = stores a value, a double == compares. 2 == 1 is False, so this branch is skipped.
print("one")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Skipped: number is not 1.
elif number == 2:
elif is short for "else if": another check that is only tried if the one above it was False. Python tests each condition from top to bottom and runs the first branch whose condition is True. 2 == 2 is True, so this branch runs.
print("two")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. This line runs.
else:
else: is the "otherwise" branch. When the if condition is False, the indented code under else: runs instead. Exactly one of the two branches runs, never both. Only runs when every check above it failed.
print("something else")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Skipped: the elif above already matched.