Conditions & Booleans
Decisions, two tracks, and the lever that picks one.
Story — the switchman at the fork
Picture a railway with a single track that splits in two. A train arrives carrying a value. Standing at the fork is a switchman with a lever. Above the lever is a question — a true-or-false question about the value the train carries.
If the answer is true, the switchman pulls the lever one way and the train takes the left track. If false, the lever goes the other way and the train takes the right track. That's an if/else: one question, two destinations, exactly one chosen.
Switchman says
See it — change the value, watch the lever
Type a value, pick an expression, then press Run. Watch the expression substitute, evaluate, and the lever throw to the chosen track. Try a value that makes the answer false — see the train go the other way.
✎ Sharpen your pencil
After watching the animation a couple of times, write one sentence describing what changes between the 'true' branch and the 'false' branch — without using the words 'if' or 'else'.
Switchman says
Try it — assemble the if/else
The five lines below build a working if/else, but they are scrambled. Reorder them so the program is correct.
Drag the pieces — or tab to one and use the ↑/↓ buttons — to put the program in order.
print("Too young")age = 21print("Can vote")else:if age >= 18:
Code it — five languages, one decision
Most languages spell the same idea three ways: the keyword (if), a true/false expression, and a body. Python uses indentation; the others use braces.
age = 21
if age >= 18:
print("Can vote")
else:
print("Too young")Build the snippet by clicking tokens from the pool, in order. Click a slot to send a token back.
- empty
- empty
- empty
- empty
- empty
- empty
Walk through it line by line
One step shows substitution; the next shows evaluation. The else block is highlighted but never runs — that is the whole point of an else.
1age = 212if age >= 18:3print("Can vote")4else:5print("Too young")
Codey says
Quiz it — make it stick
No Dumb Questions
Real questions other learners asked on this page.
Why do I need `==` instead of `=` for comparison?
Because the language has to tell the two jobs apart. `x = 5` says "make x equal to 5" (a command). `x == 5` asks "is x equal to 5?" (a question). They look similar but do completely different things, so they get different operators.What does "truthy" mean? Is true the only true thing?
Most languages let many values stand in for true or false in an if statement. In Python, anything non-empty and non-zero is "truthy" — the number 7, the string "hi", a list with anything in it. Anything empty or zero is "falsy".Why does `if/elif/elif/else` exist instead of just stacking ifs?
Because `elif` says "only check this if every if/elif above already failed." Stacking separate ifs runs every check, so two could match and run two branches. With `elif`, exactly one branch runs.