Control Flow
Making decisions with if/else and repeating work with for and while loops.
What is it?
By default, a program runs top to bottom, one line after another. Control flow is how you change that order.
Conditionals choose between paths:
- if runs a block only when a condition is true. - else runs when it's false. - elif (Python) / else if (JavaScript) checks further conditions in order. Only the first matching branch runs.
Loops repeat a block:
- A for loop runs once per item in a sequence (each item in a list, each number in a range). - A while loop runs as long as a condition stays true. Use it when you don't know in advance how many times to repeat. - break exits the loop immediately. continue skips to the next iteration.
Nesting: you can put conditionals inside loops, loops inside loops, and so on. Each level adds complexity, so keep nesting shallow.
Truthiness: conditions don't have to be literal booleans. Every value is treated as "truthy" or "falsy". Empty and zero-like values are falsy.
Explain like I'm 10
Control flow is like directions for a walk: "If the bridge is closed, take the ferry, otherwise cross" is a conditional. "Walk until you see the church" is a while loop. "Knock on each door on this street" is a for loop.
Examples
if / elif / else
temperature = 18
if temperature >= 25:
print("Hot")
elif temperature >= 15:
print("Mild") # this one runs
else:
print("Cold")Python checks conditions from top to bottom and runs only the first true branch. Indentation defines which lines belong to each branch.
for, while, break and continue
// for: once per item
const scores = [72, 45, 90, 38];
for (const score of scores) {
if (score < 50) continue; // skip failing scores
console.log("Pass:", score); // 72, 90
}
// classic counting for loop
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}
// while: until a condition changes
let attempts = 0;
while (true) {
attempts++;
if (Math.random() < 0.3) break; // stop when we "succeed"
}
console.log("Took", attempts, "attempts");for...of walks through values; the counting loop is useful when you need the index. while (true) with break is a common pattern for "repeat until".
Truthiness differs between languages
# Python falsy values: False, None, 0, 0.0, "", [], {}, set(), ()
items = []
if not items:
print("Nothing to do") # runs: empty list is falsy
name = ""
print(name or "Anonymous") # "Anonymous"
# JavaScript falsy values: false, 0, -0, 0n, "", null, undefined, NaN
# Careful: in JavaScript, [] and {} are TRUTHY.
# if ([]) { console.log("runs!"); }Empty collections are falsy in Python but truthy in JavaScript. In JavaScript, check items.length === 0 instead.
How it works
At the machine level, the CPU normally executes the next instruction in memory. Conditionals and loops compile to comparisons and jumps: "compare these values; if the result is X, jump to that instruction instead of the next one."
- An
ifbecomes: evaluate the condition; if false, jump past the block. - A loop becomes: run the block, then jump back to the condition check.
Short-circuit evaluation: and/&& stops at the first falsy operand; or/|| stops at the first truthy one. So user and user.name never touches user.name when user is None. These operators return one of the operands, not necessarily a boolean.
Loop shapes:
- range(1, 5) in Python produces 1, 2, 3, 4: the end is excluded. - A while loop must change something its condition depends on, or it runs forever.
if / else while loop
┌───────────┐ ┌───────────┐
│ condition │ ┌──►│ condition │── false ──► after loop
└─────┬─────┘ │ └─────┬─────┘
true │ false │ │ true
▼ ▼ │ ▼
[then] [else] │ [loop body]
└────┬────┘ └─────────┘
▼
next statementWhy does it exist?
Without decisions, a program would do the same thing regardless of input. Without repetition, you'd have to copy a line of code once for every item you want to process. Conditionals and loops are what let a short program handle any amount and any kind of input.
When to use it
- if/else: input validation, handling special cases, choosing behavior. - for: processing every item in a collection or a known range. - while: reading until end of input, retrying until success, game loops, or anything where the number of repetitions isn't known up front. - break: stop early once you've found what you need. - continue: skip items that don't apply without deep nesting.
When not to use it
- Avoid long if/elif chains that map a value to a result; a dictionary lookup is often clearer. - Avoid deep nesting; use early returns (guard clauses) instead. - For simple transformations of a collection, built-ins like Python comprehensions or JavaScript's map/filter can be clearer than a hand-written loop. - Avoid while when a for over a sequence expresses the same thing; it removes the risk of forgetting to update the counter.
Common mistakes
Off-by-one errors: looping one time too many or too few (
<=instead of<, or forgetting thatrange(1, 10)stops at 9).Infinite while loops because nothing inside the loop changes the condition.
Assuming empty arrays and objects are falsy in JavaScript;
if ([])is true.Ordering conditions wrongly, so a broad check (
score >= 50) runs before a narrower one (score >= 90) and hides it.Modifying a list while looping over it, which can skip items. Loop over a copy or build a new list.
Practice exercises
- Easy:
Print the numbers 1 to 30, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
- Medium:
Write a number-guessing game: pick a secret number from 1–100 and loop, telling the player "higher" or "lower" until they guess it. Print the number of guesses.
- Hard:
Print every prime number below 200 using nested loops, then make it faster by stopping each inner check at the square root and breaking early. Count how many inner-loop iterations each version runs.
Interview questions
What's the difference between `break` and `continue`?
break exits the loop entirely. continue skips the rest of the current iteration and moves to the next one.
When would you use a while loop instead of a for loop?
When the number of iterations isn't known in advance and depends on a condition, such as reading input until it's empty or retrying until success. Use for loops to iterate over a known sequence.
What values are falsy in JavaScript?
false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including [], {} and "0", is truthy.
What values are falsy in Python?
False, None, numeric zero (0, 0.0, 0j), and empty collections/strings ("", [], (), {}, set(), range(0)). Objects can define __bool__ or __len__ to control their truthiness.
What is short-circuit evaluation?
Logical operators stop evaluating as soon as the result is known: a and b skips b if a is falsy; a or b skips b if a is truthy. It's used for safe access (user and user.name) and defaults (name or "Anonymous").
What is an off-by-one error?
A loop or index that's one too high or too low, usually from mixing up inclusive and exclusive bounds or starting at 1 instead of 0. Example: for i in range(len(xs) + 1) reads past the end.
What is a guard clause?
An early return (or continue) that handles an invalid or special case at the top, so the main logic isn't nested inside an if. It flattens code and makes the happy path easier to read.
Output-prediction (Python): `for i in range(3): pass` then `print(i)`?
2. A Python loop variable is still bound after the loop, holding its last value. In JavaScript, a let loop variable isn't visible after the loop.
Does Python have a switch statement?
Since Python 3.10 it has match/case (structural pattern matching), which can serve as a switch and also destructure values. Before that, if/elif chains or dictionary lookups were used.
Scenario: a loop that removes invalid items from a list skips some of them. Why, and how do you fix it?
Removing an item shifts later items left, so the loop's index moves past the next one. Build a new filtered list instead ([x for x in xs if valid(x)] or xs.filter(valid)), or iterate over a copy.