Contents

Programming Fundamentals › Programming Basics

Control Flow

The order in which statements execute: branches, loops, returns.

Also known as: flow of control, program flow, execution order, flow control

Control flow is the order in which a program’s statements run. By default, lines run top to bottom. Control flow structures change that order.

StructureWhat it doesExamples
SequenceOne statement after anotherthe default
BranchingChoose a pathif/else, switch, ternary
LoopsRepeatfor, while
JumpsLeave early or skipreturn, break, continue
Function callsGo into another function, then come backfunctions
ExceptionsJump out when something goes wrongtry/except, throw
def first_negative(numbers):
    for n in numbers:          # loop
        if n < 0:              # branch
            return n           # jump out early
    return None                # reached only if no negative was found

Reading code by following the flow

When debugging, ask: which path did execution take? Add a print or use a debugger to step through, and see which branches ran and which loops repeated.

Habits

  • Keep it simple. Deep nesting and many exits are hard to follow. Use guard clauses to handle special cases early.
  • Make every branch intentional: what if none of the conditions match?
  • Avoid hidden flow: exceptions and callbacks make the path less visible, so document them.
  • Watch loops for exits: an infinite loop is a flow with no way out.

Asynchronous code adds another kind of flow, where work continues later (async/await).