Step 2: Add intermediate calculations
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print(f"dx = {dx}, dy = {dy}") # temporary
return 0.0
Step 3: Complete the function
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return (dx**2 + dy**2) ** 0.5
Build up one piece at a time. Test at each step.
Functions can call other functions:
def circle_area(radius):
import math
return math.pi * radius ** 2
def ring_area(outer, inner):
"""Area of a ring (donut shape)."""
return circle_area(outer) - circle_area(inner)
ring_area(5, 3) # area between radius 5 and radius 3
This is the power of decomposition!
Functions that return True or False:
def is_even(n):
"""Check if n is an even number."""
return n % 2 == 0
is_even(4) # True
is_even(7) # False
Naming convention: start with is_ or has_
We'll use these with conditionals next!
What we'll learn:
and, or, not)if/elif/else)Expressions that evaluate to True or False:
x = 5
x == 5 # True (equality)
x != 3 # True (not equal)
x > 10 # False (greater than)
x >= 5 # True (greater than or equal)
Logical operators combine conditions:
age = 25
age >= 18 and age < 65 # True
age < 18 or age >= 65 # False
not (age < 18) # True
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
Key points:
elif and else are optionalif x == y:
print("x and y are equal")
else:
if x < y:
print("x is less than y")
else:
print("x is greater than y")
Can often be simplified with elif:
if x == y:
print("x and y are equal")
elif x < y:
print("x is less than y")
else:
print("x is greater than y")
A function that calls itself:
def countdown(n):
if n <= 0:
print("Go!")
else:
print(n)
countdown(n - 1)
countdown(3) # prints: 3, 2, 1, Go!
Open Chapter 6 and Chapter 5 notebooks
Work through the examples and exercises:
if/elif/else)Questions? Ask now!
logs/wk04.md)Next session: Iteration and Search (Chapter 7)
global styles