Chapter 6 of 12
Functions in Python are first-class citizens โ they can be stored in variables, passed as arguments, and returned from other functions. This enables functional programming patterns throughout the language.
# Basic function
def greet(name):
return f"Hello, {name}!"
print(greet("Nelson")) # Hello, Nelson!
# Default parameter values
def greet(name="Stranger", greeting="Hello"):
return f"{greeting}, {name}!"
greet() # Hello, Stranger!
greet("Nelson") # Hello, Nelson!
greet("Alice", "Welcome") # Welcome, Alice!
# Keyword arguments โ pass by name, any order
greet(greeting="Hey", name="Nelson")
# Multiple return values (returns a tuple)
def get_dimensions():
return 1920, 1080 # width, height
width, height = get_dimensions()# *args โ accept any number of positional arguments
def sum_all(*numbers):
return sum(numbers)
sum_all(1, 2, 3) # 6
sum_all(1, 2, 3, 4, 5) # 15
# **kwargs โ accept any number of keyword arguments
def build_profile(**info):
for key, value in info.items():
print(f"{key}: {value}")
build_profile(name="Nelson", role="engineer", city="Nairobi")
# Lambda โ anonymous one-line functions
double = lambda x: x * 2
square = lambda x: x ** 2
# Common with sorted() and map()
courses = [("Python", 12), ("HTML", 10), ("CSS", 8)]
sorted(courses, key=lambda x: x[1]) # sort by chapter count