Key Takeaways: Control Flow, Functions, and Thinking Like a Programmer
This is your reference card for Chapter 4. Pin it, bookmark it, come back to it whenever you're staring at a blank cell wondering "how do I structure this?"
Key Concepts
-
Conditionals make your code smart. With
if,elif, andelse, your program can look at data and make decisions — categorize a vaccination rate, flag an invalid grade, choose a processing path. The condition is always a boolean expression that evaluates toTrueorFalse. -
Loops make your code tireless. A
forloop processes every item in a sequence. Awhileloop repeats until a condition changes. Together, they let you do in milliseconds what would take hours by hand — and the code doesn't care whether there are 5 items or 5 million. -
Functions make your code reusable. Instead of copying the same logic every time you need it, you define a function once and call it as many times as you want. Functions are how programmers manage complexity — each function does one thing, and they combine to do everything.
-
Functions are abstractions. This is the threshold concept. Once you name a block of logic, you can think about what it does without thinking about how it works. You stop reading code line-by-line and start reading it purpose-by-purpose.
-
Decomposition is the master skill. Breaking a big problem into small, independently testable functions is the single most important programming skill you'll develop. It's not just a coding technique — it's a way of thinking that applies to data analysis, project planning, and problem-solving in general.
-
The DRY principle saves you from yourself. Don't Repeat Yourself. If you've written the same code twice, write a function. If you've written the same function with minor variations, add a parameter.
Syntax Reference
Conditional: if / elif / else
if condition_1:
# runs if condition_1 is True
elif condition_2:
# runs if condition_1 is False and condition_2 is True
else:
# runs if all conditions above are False
- Evaluated top to bottom — stops at the first
Truecondition. elifandelseare optional. You can have justif.- You can have as many
elifbranches as you need. - Only one branch executes in an
if/elif/elsechain.
for Loop
for item in sequence:
# do something with item
sequencecan be a list, arange(), a string, or any iterable.- The loop variable (
item) takes on each value in order. - Use
range(n)to repeat somethingntimes (0 through n-1). - Use
range(start, stop)orrange(start, stop, step)for more control.
while Loop
while condition:
# do something
# MAKE SURE the condition eventually becomes False
- Checks the condition before each iteration.
- If the condition starts as
False, the body never executes. - You must update something inside the loop to avoid infinite loops.
Function Definition
def function_name(param1, param2, optional_param=default_value):
"""Docstring: describe what the function does."""
# function body
return result
defkeyword starts the definition.- Parameters are the inputs; arguments are the actual values passed.
returnsends a value back to the caller and exits the function.- A function without
returnreturnsNone. - Variables created inside the function are local (limited scope).
Common Patterns
Accumulator (Summing)
total = 0
for item in data:
total = total + item
Counting with a Condition
count = 0
for item in data:
if item > threshold:
count = count + 1
Finding the Maximum
best = data[0]
for item in data:
if item > best:
best = item
Building a Result List
results = []
for item in data:
if is_valid(item):
results.append(process(item))
Common Errors
| Error | Cause | Fix |
|---|---|---|
IndentationError |
Missing or inconsistent indentation after if, for, while, or def |
Use 4 spaces consistently; check that your editor isn't mixing tabs and spaces |
NameError (for a variable defined inside a function) |
Trying to use a local variable outside its function | Return the value from the function and capture it with a variable |
Infinite while loop (cell shows [*] forever) |
The loop condition never becomes False |
Add or fix the update step inside the loop; use Kernel > Interrupt to stop |
Function returns None unexpectedly |
Forgot the return statement |
Add return result at the end of the function |
Wrong branch executes in if/elif |
Conditions checked in the wrong order | Trace through the logic; remember elif only runs if all prior conditions were False |
TypeError: 'NoneType' ... when using a function's result |
The function returned None (missing return), and you tried to use the result |
Check the function definition for a return statement |
Pseudocode Template
Before writing code, plan in plain language:
DESCRIBE what the function should do
IDENTIFY the inputs (parameters)
IDENTIFY the output (return value)
FOR each item in the data:
IF some condition:
do something
ELSE:
do something else
RETURN the result
Then translate line by line into Python. This template covers 80% of the problems you'll encounter in data science.
What You Should Be Able to Do Now
Use this checklist to verify you've absorbed the chapter. If any item feels shaky, revisit the relevant section.
- [ ] Write an
if/elif/elsechain to categorize a numeric value into labeled bins - [ ] Construct a
forloop to process every item in a list - [ ] Use the accumulator pattern to compute a total or count
- [ ] Write a
whileloop with a condition that eventually becomesFalse - [ ] Define a function with parameters that returns a computed value
- [ ] Use a default parameter to make a function flexible
- [ ] Call one function from inside another function
- [ ] Write pseudocode before translating to Python
- [ ] Trace through a loop and conditional to predict output without running the code
- [ ] Identify and fix
IndentationError, infinite loops, and forgottenreturnstatements - [ ] Explain why the DRY principle matters and how functions support it
- [ ] Decompose a multi-step problem into small, focused functions
If you checked every box, you're ready for Chapter 5, where you'll learn the data structures that make your functions truly powerful.