Selection, Repetition and Iteration in Python
The Three Programming Constructs
Every program, regardless of language, is built from three fundamental constructs: sequence, selection, and iteration. Python implements all three. Any problem that can be solved by a computer can be solved using these three constructs alone — a theorem first proved in the 1960s and still the foundation of every language written since.
Selection — if, elif, else
Selection lets a program make decisions. Python uses if, elif (else if), and else to branch between different blocks of code depending on conditions. Only the block whose condition is True executes; all others are skipped.
# Classify an exam score
score = int(input("Enter score: "))
if score >= 70:
print("Distinction")
elif score >= 50:
print("Pass")
else:
print("Fail")
Python checks conditions from top to bottom and executes the first block whose condition is True. Once a match is found, the remaining branches are skipped. If no condition is true, the else block (if present) executes.
Python uses indentation (four spaces) to define code blocks — there are no ENDIF or END keywords. Each if, elif, and else line ends with a colon. Forgetting the colon or getting the indentation wrong causes a syntax error.
Count-Controlled Iteration — for with range()
Definite iteration uses a for loop with range(). You know in advance how many times the loop will run. The loop variable takes each value in the sequence, one at a time.
# Print the 3 times table from 1 to 10
for i in range(1, 11):
print(i, "x 3 =", i * 3)
range(1, 11) produces the integers 1, 2, 3…10. The end value (11) is excluded — this is one of the most common mistakes students make. range(5) gives 0, 1, 2, 3, 4 (starting from 0). range(1, 6) gives 1, 2, 3, 4, 5.
A running total (accumulator) is a variable that collects a sum inside a loop. Predict the output first, then trace through:
total = 0
for i in range(1, 5):
total = total + i
print(total)
Trace: i=1 → total=1; i=2 → total=3; i=3 → total=6; i=4 → total=10. Output: 10. The loop adds 1+2+3+4 = 10. Notice that total must be initialised to 0 before the loop begins — otherwise Python raises a NameError.
Iterating Over a Collection
A for loop can also iterate directly over the items in a list or the characters in a string, without needing range():
grades = ["Pass", "Fail", "Pass", "Distinction"]
for grade in grades:
print(grade)
Each time the loop runs, grade takes the next value from the list. When all items have been processed, the loop ends automatically. This pattern is used constantly when working with lists of student records, sensor readings, or transaction histories.
Condition-Controlled Iteration — while
Indefinite iteration uses a while loop. The condition is tested before each pass. If the condition is False on first entry, the body never runs.
# Keep asking until a valid score is entered
score = -1
while score < 0 or score > 100:
score = int(input("Enter a score between 0 and 100: "))
print("Valid score:", score)
The number of iterations is not fixed — it depends entirely on what the user enters. This is indefinite iteration. A while loop is the right choice when you cannot know in advance how many passes will be needed.
An infinite loop occurs when the while condition never becomes False. This usually happens because the variable in the condition is never updated inside the loop body. Always check that something inside the loop will eventually make the condition fail.
Nested Structures
Nesting means placing one construct inside another. Loops can be nested inside loops; if statements can be nested inside loops; and conditions can contain multiple levels of elif. Nested structures are used for processing 2D data, multi-condition menus, and grid operations.
Count how many scores in a list are above 60:
scores = [45, 72, 88, 30, 65]
count = 0
for score in scores:
if score > 60:
count = count + 1
print("Scores above 60:", count)
Predict: The loop visits 45 (no), 72 (yes, count=1), 88 (yes, count=2), 30 (no), 65 (yes, count=3). Output: Scores above 60: 3. A common mistake is indenting the print inside the loop, which would print after every iteration instead of once at the end.
Single Entry and Exit Points
Well-structured code has a single entry point and a single exit point for each block. In Python, each loop or selection block has one entry (the first line) and one exit (when the condition fails or the block ends). Avoid designs that “break out” of the middle of multiple nested loops — these make code harder to trace, test and maintain.
Use for when: you know the number of iterations in advance, or you are processing every item in a list or string. Examples: printing a times table up to 12, processing each student's score in a class list.
Use while when: the number of iterations depends on user input or a changing condition. Examples: a login prompt that repeats until the correct password is entered, a sensor loop that runs until a threshold is crossed.