typestar

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

  1. An if/elif ladder returns at the first true branch.
  2. else catches everything that fell through.
  3. The one-line conditional expression handles simple picks.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 7 in Flow control, step 16 of 72 in Language basics.

← Previous Next →