Chapter 4 of 11
~13 minControl Flow
Control flow statements decide which code runs and how many times - conditionals branch based on a test, loops repeat work, and break/continue give you fine-grained control over a loop in progress.
if / elif / else
An if statement runs a block only when its condition is True. elif lets you check additional conditions in sequence if the earlier ones were False, and a final else catches everything that did not match any prior condition. Python evaluates these top to bottom and stops at the first branch whose condition is True, skipping the rest entirely.
Try it yourself
A simple age-bracket checkage = 20 if age < 13: print("Child") elif age < 20: print("Teenager") else: print("Adult")
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
for Loops vs. while Loops
A for loop iterates directly over a sequence - a list, string, range, or any other iterable - running once per item, so the number of iterations is determined by the length of that sequence. A while loop instead keeps running as long as a condition stays True, which is the right tool when you do not know the number of iterations ahead of time, such as waiting on user input or polling until some state changes.
Try it yourself
The same idea expressed with for and with whilefor i in range(1, 4): print("for:", i) count = 1 while count < 4: print("while:", count) count += 1
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
break and continue
break exits the enclosing loop immediately, skipping any remaining iterations entirely. continue instead skips only the rest of the current iteration and moves straight on to the next one, without leaving the loop. Both only affect the nearest enclosing loop, not any loop further out.
Try it yourself
break stops the loop; continue skips just one iterationfor i in range(1, 10): if i == 5: break print("break demo:", i) for i in range(1, 6): if i % 2 == 0: continue print("continue demo:", i)
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Nested Loops
A nested loop places one loop entirely inside another, so the inner loop runs to completion for every single iteration of the outer loop. This is a common pattern for working with grid-like or multi-dimensional data, such as printing coordinates for every row-and-column pair in a table.
Try it yourself
Printing every (row, col) pair in a 3x3 gridfor row in range(1, 4): for col in range(1, 4): print(f"({row},{col})", end=" ") print()
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Coding challenge
Write a function first_common_multiple_under(limit, a, b) that searches numbers from 1 up to limit and returns the first one that is evenly divisible by both a and b, or None if none is found within that range. Call it to find the first common multiple of 4 and 6 under 50.
# Write your solution here
Press Run to execute your Python. The first run loads Python in your browser (a few seconds).
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/51. What determines whether an elif branch runs?
2. When is a while loop generally the better choice over a for loop?
3. What is the difference between break and continue inside a loop?
4. In a nested loop where the outer loop runs 3 times and the inner loop runs 3 times per outer iteration, how many total inner-loop executions occur?
5. Does break or continue inside an inner loop affect an outer loop that contains it?