'negative'
Functions and Control Flow
Learn if-statements, loops, and reusable Python functions.
Learning Objectives
- Use
if,elif, andelseto make decisions. - Use loops to process repeated values.
- Define reusable functions.
- Understand why functions make quantitative code easier to maintain.
Motivation
Quantitative Python work often repeats the same logic: classify a value, compute a running total, or apply a formula to several inputs. Functions and control flow make that logic explicit.
Conditional Logic
The package includes a small helper with the same logic.
('negative', 'zero', 'positive')
Loops
Loops let us process a sequence of values.
6
Functions
A function gives a name to a reusable computation.
100.0
Running Totals
[100.0, 80.0, 130.0, 140.0]
Common Mistakes
Indentation Is Syntax
Python uses indentation to decide what belongs inside an if, loop, or function. Misaligned code changes the meaning.
Forgetting return
If a function does not return a value, Python returns None.
Practice
- Write a function that doubles a number.
- Write an
ifstatement that labels a number as “large” if it is above100. - Use a loop to sum
[2, 4, 6, 8]. - Use
cumulative_sumon[10, -3, 7].
Solutions
TipSolution 1
Answer:
def double(value):
return 2 * value
TipSolution 2
Answer:
if value > 100:
label = "large"
else:
label = "not large"
TipSolution 3
Answer: 20.
total = 0
for value in [2, 4, 6, 8]:
total = total + value
TipSolution 4
Answer: [10, 7, 14].
The running totals are 10, then 10 - 3 = 7, then 7 + 7 = 14.