Functions and Control Flow

Learn if-statements, loops, and reusable Python functions.

Learning Objectives

  • Use if, elif, and else to 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

value = -2

if value < 0:
    label = "negative"
elif value > 0:
    label = "positive"
else:
    label = "zero"

label
'negative'

The package includes a small helper with the same logic.

from edumath.python_fundamentals import classify_number

classify_number(-2), classify_number(0), classify_number(5)
('negative', 'zero', 'positive')

Loops

Loops let us process a sequence of values.

values = [1, 2, 3]
total = 0

for value in values:
    total = total + value

total
6

Functions

A function gives a name to a reusable computation.

def simple_interest(principal, rate, years):
    return principal * rate * years

simple_interest(1000, 0.05, 2)
100.0

Running Totals

from edumath.python_fundamentals import cumulative_sum

cumulative_sum([100, -20, 50, 10])
[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

  1. Write a function that doubles a number.
  2. Write an if statement that labels a number as “large” if it is above 100.
  3. Use a loop to sum [2, 4, 6, 8].
  4. Use cumulative_sum on [10, -3, 7].

Solutions

Answer:

def double(value):
    return 2 * value

Answer:

if value > 100:
    label = "large"
else:
    label = "not large"

Answer: 20.

total = 0
for value in [2, 4, 6, 8]:
    total = total + value

Answer: [10, 7, 14].

The running totals are 10, then 10 - 3 = 7, then 7 + 7 = 14.