Control Structures - Study Notes
Chapter Summary
Python programs execute sequentially by default, but control structures allow developers to alter this path through decision-making branches and loops. This chapter details branching methods such as simple if, if-else, and nested if-elif-else structures, iterative patterns like while and for loops, and jump statements like break, continue, and pass.
Learning Objectives
- Explain the concept of execution flow control in Python.
- Apply conditional branching structures to evaluate logic.
- Implement entry-controlled loops to perform repetitive tasks.
- Regulate loop execution and termination using jump statements.
- Understand the purpose and application of the pass statement.
Key Concepts and Definitions
- Control Structure: A program statement that transfers execution control to another part of the program.
- Sequential Statements: Statements executed one after another in order of appearance.
- Branching: Decision-making constructs that select specific execution blocks based on a conditional statement.
- Looping: Repeating a block of code multiple times or until a condition is satisfied.
- Indentation: The mandatory use of consistent whitespace to define code blocks instead of curly braces.
- Jump Statement: Commands such as break, continue, or pass that unconditionally redirect control flow.
Worked Methods
Finding the Smallest of Three Numbers
We use a nested conditional structure to evaluate and compare three distinct numerical inputs pairwise, assigning the minimum value to a variable.
num1, num2, num3 = 12, 5, 8
if num1 <= num2 and num1 <= num3:
smallest = num1
elif num2 <= num1 and num2 <= num3:
smallest = num2
else:
smallest = num3
Generating Steps with the range() Function
To print all even numbers between 2 and 20 (inclusive), the range function is called with a step value of 2 inside an iterative loop.
for i in range(2, 21, 2):
print(i)
Common Exam Traps
- Indentation Error: Mixing spaces and tabs or having different levels of indentation in the same block causes immediate compile-time errors. Always keep block alignment identical.
- Exclusive Range Limit: The stop parameter in the range function is exclusive. Generating values up to 100 requires the stop parameter to be 101.
- Infinite Loops: Failing to modify the control variable inside a while loop keeps the condition True indefinitely, freezing program execution.
- Missing Colons: Omitting the colon at the end of conditional headers or loop statements generates a syntax error.
Exam Tips
- Manually trace loop variable states on paper when solving output-based questions.
- Ensure numeric inputs are explicitly converted from strings using the int() function before comparison.
- Remember that loop else blocks do not execute if the loop is terminated prematurely by a break statement.
- Use the pass statement to safely represent empty blocks without triggering syntax errors.