A fork in the road with a signpost

Conditional Statements

The analogy

A program normally reads top to bottom like a recipe. A conditional is a fork in the road: the program walks up, reads the signpost โ€” a yes/no question like "is age >= 18?" โ€” and takes exactly ONE of the paths. if is the fork, elif adds more prongs ("if not that, then is it this?"), and else is the path for "none of the above". The crucial rule: in an if/elif/else chain, the FIRST true signpost wins and every later prong is skipped without even being read. Order your questions from most specific to most general, or the general one will greedily catch everything first.

Visualizer

The fork in the road

step 1 / 6
startscore>=80?greatscore>=50?passretry

A program is a road. A conditional is a fork: each diamond asks one yes/no question and the walker takes exactly one branch.score = 73

๐Ÿ“– In depth โ€” the full reference

What counts as false โ€” the full list

Python (falsy)JavaScript (falsy)
False, Nonefalse, null, undefined
0, 0.0, 0j0, -0, 0n, NaN
"" (empty string)"" (empty string)
[], (), {}, set()โ€” (empty arrays/objects are TRUTHY in JS!)

Python conditional forms

  • if / elif / else โ€” first true branch wins, everything after is skipped unread.
  • Ternary reads middle-out: grade = "pass" if score >= 50 else "retry".
  • match/case (3.10+) is the multiway switch: match cmd: case "quit": ... case _: ...
  • if items: is the idiom for "non-empty"; if x is None: for "unset" โ€” because 0 and "" are falsy but often valid values!
  • Guard clauses keep the happy path flat: if not user: return early.
score = 73

if score >= 80:        # most specific first!
    grade = "great"
elif score >= 50:
    grade = "pass"
else:
    grade = "retry"

print(grade)           # pass
Check yourself

score = 90. Chain: if score >= 50: print("pass") / elif score >= 80: print("great") / else: .... What prints?

Practice โ€” write it yourself

grade(score) returns "great" for 80+, "pass" for 50-79, "retry" below 50. Mind the chain order!

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser