PyPython · Lesson 4 of 14

Functions

Functions are reusable blocks of code. Write once, call many times. This is the foundation of not hating yourself when you have to change something.

Define functions with the def keyword. Parameters can have default values, and Python supports both positional and keyword arguments when calling functions.

Python
# Basic function
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))   # Hello, Alice!

# Default parameter values
def greet_with_title(name, title="Dr."):
    return f"Hello, {title} {name}!"

print(greet_with_title("Smith"))           # Hello, Dr. Smith!
print(greet_with_title("Jones", "Prof."))  # Hello, Prof. Jones!

# Multiple return values (returns a tuple)
def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 4, 1, 5, 9, 2, 6])
print(lo, hi)   # 1 9

# *args — variable number of arguments
def total(*args):
    return sum(args)

print(total(1, 2, 3, 4))   # 10

# **kwargs — keyword arguments as a dict
def describe(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

describe(name="Alice", age=30, city="Paris")

Lambda functions are anonymous single-expression functions, useful for short operations passed to higher-order functions like sorted(), map(), and filter().

Python
# Lambda: lambda parameters: expression
square = lambda x: x ** 2
print(square(5))   # 25

# Common use: sorting with a custom key
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
sorted_by_age = sorted(people, key=lambda p: p[1])
print(sorted_by_age)   # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]

# map() — apply function to every element
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)   # [1, 4, 9, 16, 25]

# filter() — keep elements where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)   # [2, 4]