06. First-Class Functions
In Python, functions are "first-class citizens," meaning they can be treated like any other object.
Assigning Functions to Variables
def greet(name):
return f"Hello, {name}"
say_hello = greet
print(say_hello("Alice"))
Passing Functions as Arguments
def apply(func, value):
return func(value)
def square(x): return x*x
print(apply(square, 5))
Returning Functions from Functions
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = make_multiplier(2)
print(double(10)) # 20
Practice Challenge
Write a function make_adder(n) that returns a function which adds n to its input.
Wrap-Up
- Functions can be assigned, passed, and returned.
- This enables higher-order functions and functional programming in Python.