Chapter 6: Functions
Defining Functions
A function is like a "vending machine" — you insert input (parameters) and it outputs a result (return value). Wrapping repeated code into functions makes your code cleaner.
bash
# Basic function definition
def greet(name):
"""Say hello to someone (this is a docstring)"""
return f"Hello, {name}! Welcome to Python!"
message = greet("Alice")
print(message)
# View the docstring
print(greet.__doc__))bash
Hello, Alice! Welcome to Python!
Say hello to someone (this is a docstring)Parameter Types In-Depth
bash
# 1. Positional parameters
def add(a, b):
return a + b
print(f"10 + 20 = {add(10, 20)}")
# 2. Keyword parameters (can be passed in any order)
def profile(name, age, city):
return f"{name}, {age} years old, from {city}"
print(profile(age=25, city="Beijing", name="Bob"))
# 3. Default parameters
def power(base, exponent=2):
return base ** exponent
print(f"2 to the power of 3 = {power(2, 3)}")
print(f"5 squared = {power(5)}") # Uses default value
# 4. Variable-length args *args (packs into a tuple)
def total(*args):
print(f" Received args: {args}")
return sum(args)
print(f"Sum = {total(1, 2, 3, 4, 5)}")
# 5. Keyword variable-length args **kwargs (packs into a dict)
def show_info(**kwargs):
for key, value in kwargs.items():
print(f" {key}: {value}")
show_info(name="Alice", age=18, hobby="Coding")bash
10 + 20 = 30
Bob, 25 years old, from Beijing
2 to the power of 3 = 8
5 squared = 25
Received args: (1, 2, 3, 4, 5)
Sum = 15
name: Alice
age: 18
hobby: CodingLambda Anonymous Functions
bash
# lambda is a one-line mini function
square = lambda x: x ** 2
print(f"3 squared = {square(3)}")
# Commonly used with sorted, map, filter, etc.
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
# Sort by score
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(f"Score ranking: {sorted_students}")
# map: apply function to each element
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(f"Doubled: {doubled}")
# filter: filter elements
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {evens}")bash
3 squared = 9
Score ranking: [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
Doubled: [2, 4, 6, 8, 10]
Even numbers: [2, 4]Decorators
A decorator is like "getting dressed" for a function — it doesn't change the function itself but adds extra features (like timing, logging, or permission checks).
bash
import time
# Define a timer decorator
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f" ⏱️ {func.__name__} took: {elapsed:.4f}s")
return result
return wrapper
# Use decorator with @ syntax
@timer
def slow_function(n):
"""An intentionally slow function"""
total = 0
for i in range(n):
total += i
return total
result = slow_function(1_000_000)
print(f"Result: {result}")bash
⏱️ slow_function took: 0.0512s
Result: 499999500000