all algorithms
algorithm 02
Conditions
A switchman reads the boolean expression, throws the lever, and the train takes the chosen track. Same logic — if/else — in four languages.
02 / Conditions
if (x > threshold)
- x
- 7
- threshold
- 5
- branch
- —
step 0
- 0
def route(x, threshold): - 1
if x > threshold: - 2
return "if branch" - 3
else: - 4
return "else branch"
Set values, then send the train.
What you just watched
A condition is a question the program asks at runtime, then commits to one branch based on the answer. The lever is the conditional expression; the two tracks are the if and else blocks. Try setting x = threshold — the strict greater than comparison evaluates to false, and the train takes the else branch.
Conditions cost nothing to evaluate (O(1)), which is why they show up everywhere — inside loops, inside searches, inside sorts. You'll see the same lever metaphor return as part of every algorithm in this set.