Control Flow
Chapter 2: Control Flow
Control flow determines the order in which your code executes. Instead of running line by line from top to bottom, you can make decisions, repeat actions, and skip sections based on conditions. This chapter covers Python's fundamental control flow structures: conditional statements, loops, and flow control keywords.
Making Decisions with Conditional Statements
Programs need to make decisions based on data. Python's if statement lets you execute code only when certain conditions are true. Here's the basic structure:
The condition age >= 18 evaluates to either True or False. If true, Python executes the indented code below. Indentation is crucial in Python—it defines which code belongs to the if statement.
Adding Alternatives with else and elif
Often you need to handle multiple possibilities. The else clause runs when the condition is false:
For multiple conditions, use elif (short for "else if"):
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score: {score}")
print(f"Your grade is: {grade}")Python checks each condition in order, stopping at the first true one. Only one branch executes. This example demonstrates how to categorize values into ranges—a common programming pattern.
Repeating Actions with for Loops
Loops let you repeat code multiple times without writing it over and over. The for loop iterates over sequences like lists, strings, or ranges. The most common use is with range(), which generates a sequence of numbers:
# Print numbers 0 through 4
for i in range(5):
print(i)
# Print even numbers from 2 to 10
for num in range(2, 11, 2):
print(num)The range() function accepts three arguments: start (inclusive), stop (exclusive), and step. If you provide one argument, it's the stop value, starting from 0.
Iterating Over Collections
The real power of for loops appears when iterating over collections like lists or strings:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
print("\nIterating over string characters:")
# Iterate over each character in a string
message = "Python"
for char in message:
print(char)Each iteration assigns the next item to the loop variable (fruit or char), making it simple to process every element in a collection. This pattern appears constantly in Python programming.
Repeating with Conditions: while Loops
While for loops iterate a specific number of times, while loops continue as long as a condition remains true. They're perfect when you don't know in advance how many iterations you'll need:
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1This loop prints numbers 0 through 4, just like a for loop would. The key difference: while loops check the condition before each iteration. If the condition starts false, the loop body never runs.
Be careful with while loops—if the condition never becomes false, you create an infinite loop. Always ensure something inside the loop will eventually make the condition false.
Controlling Loop Flow: break and continue
Sometimes you need finer control over loop execution. Python provides two keywords for this: break and continue.
The break statement immediately exits the loop entirely:
# Find the first number divisible by 7
for num in range(1, 100):
if num % 7 == 0:
print(f"First number divisible by 7: {num}")
breakThe continue statement skips the rest of the current iteration and moves to the next one:
# Print odd numbers only
for num in range(10):
if num % 2 == 0:
continue
print(num)These keywords work in both for and while loops. Use break to exit early when you find what you're looking for. Use continue to skip certain items without processing them.
Nested Loops and Complex Flow
You can place loops inside other loops, creating nested structures for working with multi-dimensional data:
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} × {j} = {i * j}")
print("---")The inner loop completes all its iterations for each iteration of the outer loop. This creates a grid-like pattern useful for processing tables, matrices, or generating combinations.
Similarly, you can nest if statements inside loops and vice versa, combining control structures to create sophisticated logic. Keep nesting to reasonable levels—deeply nested code becomes hard to read and maintain.
Best Practices for Control Flow
Write clear conditions using comparison operators: ==, !=, <, >, <=, >=. Combine conditions with and, or, and not. For example: if age >= 18 and has_license:.
Choose the right loop type. Use for when you know how many times to iterate or when processing a collection. Use while when repeating until a condition changes. Avoid infinite loops by ensuring loop conditions can become false.
Keep loop bodies short and focused. If a loop grows complex, extract logic into functions. This makes code easier to test and understand.
Try It Yourself: Practice Exercises
Exercise 1: FizzBuzz
Write a program that prints numbers 1 to 20. For multiples of 3, print "Fizz" instead. For multiples of 5, print "Buzz". For multiples of both, print "FizzBuzz".
Exercise 2: Number Guessing
Create a simple number guessing game. Set a target number (e.g., 7). Use a while loop to let the user guess. Print "Higher" or "Lower" until they guess correctly.
Exercise 3: List Processing
Given a list of numbers, create a new list containing only even numbers. Use a for loop and an if statement to filter the values.
These exercises reinforce the control flow patterns you've learned. Start simple, test frequently, and build complexity gradually.
What's Next?
You've mastered Python's fundamental control flow: making decisions with conditionals, repeating actions with loops, and controlling flow with break and continue. These building blocks appear in virtually every program you'll write.
In the next chapter, we'll explore functions—reusable blocks of code that help you organize and structure larger programs. You'll learn to write your own functions, pass data to them, and return results.
📝 Test Your Knowledge: Control Flow
Take this quiz to reinforce what you've learned in this chapter.