Chapter 5: Execution Control
Chapter 5: Execution Control
Controlling the flow of your program is essential for writing effective data science code. Python provides powerful control structures for loops, conditionals, and exception handling that let you manage how your code executes.
For Loops: Iterating Over Data
The for loop is the workhorse of data iteration in Python. It allows you to process each item in a collection efficiently.
Using range() to Generate Numbers
The built-in range() function creates an iterable sequence of numbers:
Simple For Loop with Range
Use range() with for to repeat an action multiple times:
Notice that range(1, 6) starts at 1 and stops before 6, giving you five iterations.
Iterating Over Lists
The most common pattern in data science - iterating over a list:
Iterating with Index and Value
Use enumerate() to get both the index and value:
Iterating Over Multiple Lists
Use zip() to iterate over multiple lists simultaneously:
List Comprehensions
A concise way to create lists using for loops:
List comprehensions are faster and more Pythonic for simple transformations.
While Loops: Repeating Until a Condition
While loops continue executing until a condition becomes false. They're useful when you don't know how many iterations you need in advance.
Basic While Loop
While Loop with Generator
Generators can be used with while loops for efficient iteration:
The else clause runs when the while condition becomes false (but not if you break out).
Infinite Loop with Break
Sometimes you want an infinite loop that exits based on a condition:
Exception Handling: Expecting the Unexpected
Robust code handles errors gracefully. Python's try/except mechanism lets you catch and handle exceptions.
Basic Try/Except
Catch specific exceptions to handle errors:
This prevents your program from crashing when the list is empty.
Catching Multiple Exception Types
Handle different exceptions differently:
Using Finally for Cleanup
The finally block always executes, even if an exception occurs:
Getting Exception Details
Access the exception object for more information:
Conditionals: Making Decisions
Conditional statements let your code make decisions based on data.
If/Elif/Else Blocks
The standard way to branch between multiple conditions:
Comparison Operators
Python supports rich comparison operators:
Ternary Conditional Expression
Single-line conditional assignment:
Multiple Conditions with and/or
Combine conditions logically:
Checking Membership
Use in to check if an item exists in a collection:
Break, Continue, and Pass
Special keywords that control loop execution.
Using Break to Exit Early
Exit a loop immediately:
Using Continue to Skip Iterations
Skip the rest of the current iteration and continue with the next:
Only "Moby Dick" gets printed because continue skips the print for other whales.
Using Continue for Filtering
A practical use case - processing only valid data:
Using Pass as a Placeholder
pass does nothing - it's a placeholder for future code:
Pass in Conditional Blocks
Sometimes you need an empty branch:
Combining Control Structures
Real-world code often combines these control structures.
Nested Loops with Conditionals
Exception Handling in Loops
While Loop with Multiple Exit Conditions
Key Takeaways
- For Loops: Use for iterating over sequences (lists, ranges, etc.)
- While Loops: Use when you don't know how many iterations you need
- Try/Except: Always handle potential errors in production code
- If/Elif/Else: Use for branching logic based on conditions
- Break: Exit a loop immediately
- Continue: Skip to the next iteration
- Pass: Placeholder for empty code blocks
These control structures are the building blocks of algorithm implementation. Master them, and you can express any computational logic clearly and efficiently.
Quiz
Further Reading
📝 Test Your Knowledge: Chapter 5: Execution Control
Take this quiz to reinforce what you've learned in this chapter.