Skip to content

Programming Fundamentals & OOP

Control Flow: Conditionals and Loops

Control flow is the general term for anything that changes the order code executes in, beyond running top to bottom. Conditionals such as if, elif and else choose which block of code runs based on whether an expression is true or false. Loops such as for and while repeat a block, either a known number of times or until a condition changes. Every mainstream language implements both ideas, even though the exact keywords and syntax differ.

Why it matters

Branching is what makes a program respond to its input at all
Without an if statement, a program would do exactly the same thing on every run regardless of what data it receives.
Loops remove the need to write out repeated logic by hand
Processing a thousand rows takes the same few lines as processing ten, because the loop, not the programmer, repeats the work.
Misreading control flow is one of the most common debugging failures
A bug that looks like wrong data is very often a loop that runs one time too many or too few, or a condition that is true when the programmer assumed it was false.
Short-circuit evaluation changes what actually executes, not just the result
In 'a and b', b is never evaluated if a is already false - code that relies on b running as a side effect will silently not run.

Branching: if, elif, and else

An if statement evaluates a boolean expression and runs its block only when that expression is true; elif checks another condition only if every earlier one was false; else catches everything else. Python also short-circuits and/or: in a and b, b is only evaluated if a is already true, which is both a performance optimization and a common idiom for guarding against an error, such as checking a value exists before using it, in the same expression.

Python
score = 82

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'

print(grade)  # B

Loops: known repetition vs repetition until a condition changes

A for loop repeats a block once per item in a known sequence - a range of numbers, a list, the characters of a string - and stops naturally when the sequence is exhausted. A while loop repeats a block as long as a condition stays true, which is the right tool when you do not know in advance how many repetitions you need, such as reading input until a user signals they are done. Both support break, which exits the loop immediately, and continue, which skips to the next iteration without finishing the current one.

Python
total = 0
n = 1
while total < 50:
    total += n
    n += 1

print(total, n)  # the first total that reaches or passes 50, and the n that got it there

Nesting and early exits

Loops and conditionals can contain each other freely, but nesting has a real readability cost: a condition inside a loop inside another condition asks the reader to track several states of the world at once. A common fix is the guard clause - checking for an invalid or trivial case first and returning or continuing immediately, so the rest of the block can assume the normal case without an extra layer of indentation. This is a style choice, not a language feature, but it is one of the most reliable ways to keep control flow readable as a function grows.

Mistakes people make here

Off-by-one errors in loop bounds
range(1, 5) produces 1 through 4, not 5, because the stop value is exclusive. This is consistent with indexing starting at 0, but it still catches people who expect the endpoint to be included.
Writing a while loop that never updates its own condition
A while loop only stops when its condition becomes false; forgetting to change the variable the condition depends on produces an infinite loop that has to be killed from outside the program.
Nesting conditionals three or four levels deep instead of returning early
Each level of nesting adds a state the reader has to hold in their head simultaneously. A guard clause that handles the exceptional case first and exits usually reads more clearly than an equivalent deeply nested if.
Reaching for a while loop with a manual counter where a for loop already does the job
A for loop over range(n) or a collection cannot forget to update its own counter and cannot run one iteration too many by mistake - a hand-rolled while loop with an index variable can do both.

Strengths and trade-offs

Where it is strong

  • A small set of constructs - if, for, while - combine to express almost any decision or repetition a program needs.
  • For loops over a known collection remove an entire category of bounds bugs compared to a hand-managed counter.
  • Guard clauses and early returns keep the common case flat and readable even as a function's edge cases grow.

The trade-offs

  • Deeply nested branches get harder to reason about faster than their individual simplicity suggests.
  • A while loop's flexibility is also a risk: nothing stops it from running forever if its condition is written wrong.
  • The concept transfers between languages but the syntax rarely does - Python has no C-style counting for loop, and had no switch-like statement until match was added in 3.10.

Who needs this

Everyone who writes code, from the first program onward. It is also one of the few concepts where the underlying idea is identical across virtually every language, even when the exact syntax is not.

Questions about control flow: conditionals and loops

What's the real difference between a for loop and a while loop?
A for loop iterates over a known sequence and stops when it is exhausted; a while loop repeats based on a condition and can run zero times, a fixed number of times, or indefinitely depending on how that condition changes. Use for when you're iterating over something; use while when you're waiting for a state to change.
What's the difference between break and continue?
break exits the loop entirely, skipping any remaining iterations. continue skips only the rest of the current iteration and moves on to the next one, still checking the loop's condition normally.
Why do some languages skip evaluating the second half of an and or or?
It's called short-circuit evaluation: if the first operand of and is already false, the whole expression must be false regardless of the second operand, so evaluating it would be wasted work - and, in patterns that check a value exists before using it, actively unsafe to evaluate.
Is recursion a form of control flow?
Yes - a function calling itself is another way to repeat work, as an alternative to a loop. It's covered in more depth alongside functions, since it depends on understanding how function calls and scope work first.

The primary source

Related concepts

← All concept guides