Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • write small utility functions
  • return processed values from lists and strings
  • compose functions for cleaner code

Example 1: maximum of two numbers

def maximum(a, b):
    if a > b:
        return a
    return b

Example 2: count vowels

def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    return count

Example 3: sum of list

def list_sum(nums):
    total = 0
    for x in nums:
        total += x
    return total

Example 4: factorial function

def factorial(n):
    if n < 0:
        return None
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    return fact

Multiple returns via tuple

def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3, 9, 1, 5])
print(lo, hi)

Exam hints and traps

  • use return for reusable function result
  • returning None can be intentional for invalid case
  • function may return tuple if multiple values are needed

Quick practice

  1. Write function to count even numbers in a list.
  2. Write function to reverse a string.
  3. Write function to return both sum and average of a list.