Functions II
CDS1010: Week 6
Wiedemann • Fall 2025
Functions as Contracts/Promises
- Write functions so the caller can focus on what it does, not how it does it
- Describe what it does in a docstring
def clean_name(raw):
"""
Trim whitespace from the raw string and convert it to title case.
"""
text = raw.strip()
return text.title()
Multiple Returns and Unpacking
- A function can return more than one value, separated by a comma
- These returns can be unpacked into separate names when calling
def min_max(numbers):
"""Return the smallest and largest values from the list."""
smallest = numbers[0]
largest = numbers[0]
for value in numbers:
if value < smallest:
smallest = value
if value > largest:
largest = value
return smallest, largest
lo, hi = min_max([3, 9, 2, 7])
print(f"The smallest value is {lo} and the largest value is {hi}.")
Helper Functions
- A function can be called by another function
- A helper function is a small, specialized function that helps another function do its job
- Helper functions keep code organized and readable, and make it easier to extend
def compute_average(nums):
"""Return the arithmetic mean of a list of numbers."""
total = 0
for n in nums:
total += n
return total / len(nums)
def show_average(nums):
"""Print a message with the average of a list of numbers."""
avg = compute_average(nums) # helper function called
print("Average:", avg)