If, elif, else in Python
Branching: choosing a path based on conditions, top to bottom.
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
mark = grade(85)
verdict = "pass" if mark != "F" else "fail"
How it works
- An
if/elifladder returns at the first true branch. elsecatches everything that fell through.- The one-line conditional expression handles simple picks.
Keywords and builtins used here
defelifelsegradeifreturn
The run, in numbers
- Lines
- 13
- Characters to type
- 182
- Tokens
- 63
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 44 seconds.
Step 1 of 7 in Flow control, step 16 of 72 in Language basics.