On This Page
Prerequisites
This chapter builds on Chapter 3: Variables & Basic Types. Before proceeding, confirm you can:
- Declare and reassign variables using =, including int, float, str, and bool types.
- Evaluate comparison expressions with ==, !=, <, >, <=, and >=.
- Combine conditions using the boolean operators and, or, and not.
- Work with Python's list type, including indexing and checking length with len().
- Run Python scripts from the terminal and interpret basic error messages such as SyntaxError and IndentationError.
Learning Goals
-
Use if/elif/else for decisions
- Use if/elif/else to implement decision logicthat directs program execution down distinct paths based on runtime conditions
- Write single if statements that guard a block of code behind a boolean expression, executing it only when the condition evaluates to True
- Chain elif clauses to test multiple mutually exclusive conditions in sequence, ensuring exactly one branch executes per evaluation
- Attach else as a catch-all terminal branch that handles every case not matched by preceding if or elif conditions
- Nest conditional blocks inside other conditionals to express multi-dimensional decision trees, such as validating both user role and permission level before granting access
-
- Iterate with for loops to process collections and rangeswithout manually tracking index variables or writing repetitive code
- Loop over list, tuple, str, and dict objects using Python's for item in iterable syntax, accessing each element directly rather than by position
- Generate numeric sequences with range() to control iteration counts, step sizes, and start/stop boundaries for tasks like batch processing or fixed-repetition calculations
- Use enumerate() to access both the index and the value during iteration, eliminating the need for a separate counter variable
- Apply the zip() function to iterate over two or more sequences in parallel, pairing corresponding elements for comparison or transformation
-
- Repeat actions with while loops driven by dynamic conditionsthat cannot be determined before the loop begins
- Construct a while loop that continues executing as long as its condition expression remains True, re-evaluating the condition at the start of every iteration
- Implement sentinel-controlled loops that wait for a specific signal value — such as user input equal to "quit" or an API response status of 200 — before terminating
- Avoid infinite loops by ensuring every iteration modifies at least one variable involved in the loop's exit condition, and recognize the warning signs when a loop never terminates
-
Control loops with break and continue
- Control loop execution with break and continueto handle early exits and selective skipping within both for and while loops
- Use break to terminate a loop immediately when a target condition is met, such as finding the first matching record in a dataset or exceeding a retry limit
- Use continue to skip the remaining body of the current iteration and advance to the next cycle, which is useful for filtering out invalid entries or ignoring non-critical errors
- Combine break with an else clause on a loop to distinguish between loops that completed naturally and loops that exited early, a pattern frequently used in search algorithms
Key Terminology
Conditional
A statement that evaluates a boolean expression and executes a block of code only when the expression is **True**.
if statement
The primary conditional keyword in Python that tests a single condition and runs its indented block when the condition holds.
elif clause
Short for "else if," a follow-up branch that tests an additional condition only when all preceding **if** and **elif** conditions evaluated to **False**.
else clause
The terminal branch of a conditional chain that executes when none of the preceding **if** or **elif** conditions matched.
Boolean expression
A combination of values, variables, and operators that resolves to either **True** or **False**, used as the gatekeeper for conditionals and loops.
for loop
A control flow construct that iterates over each element in an iterable object, executing its body once per element.
Iterable
Any Python object capable of returning its elements one at a time, including **list**, **tuple**, **str**, **dict**, **set**, and generator objects.
range()
A built-in function that produces a sequence of integers defined by start, stop, and step arguments, commonly used to drive **for** loops a specific number of times.
while loop
A control flow construct that repeatedly executes its body as long as its condition expression evaluates to **True**, checking the condition before each iteration.
Infinite loop
A **while** loop whose condition never becomes **False**, causing the program to run indefinitely unless interrupted by **break** or an external signal.
break
A statement that immediately terminates the innermost enclosing loop, transferring execution to the first line after that loop's block.
continue
A statement that skips the remaining body of the current loop iteration and jumps back to the loop's condition check or next element.
Loop variable
The variable declared in a **for** loop header that takes on the value of each successive element from the iterable during iteration.
Sentinel value
A predefined value that signals a **while** loop to stop, such as a user typing **"exit"** or a function returning **None**.
Nested loop
A loop placed inside the body of another loop, where the inner loop completes all its iterations for each single iteration of the outer loop.
Loop else clause
An optional **else** block attached to a **for** or **while** loop that executes only when the loop terminates naturally without encountering a **break**.
Short-circuit evaluation
Python's behavior of stopping boolean expression evaluation as soon as the result is determined — **and** stops on the first **False**, **or** stops on the first **True**.
Truthy and falsy
Values that evaluate to **True** or **False** in a boolean context; **0**, **0.0**, **""**, **[]**, **{}**, and **None** are falsy, while most other objects are truthy.