Back
+15 XP
Concept

First-Class Functions: Passing Functions as Data

In Python, functions are first-class citizens 🎟️. You can assign functions to variables, store them in lists, and pass them as arguments to other functions.

python
def shout(text):
    return text.upper() + "!"

# Function assigned to a variable:
speaker = shout
print(speaker("hello"))  # HELLO! 📢

# Passed into another function:
def run_op(func, val):
    return func(val)

print(run_op(shout, "python"))  # PYTHON! 🚀

# 31. First-Class Functions: Passing Functions as Data In Python, functions are first-class citizens 🎟️. You can assign functions to variables, store them in lists, and pass them as arguments to other functions: ```python def shout(text): return text.upper() + "!" # Function assigned to a variable: speaker = shout print(speaker("hello")) # HELLO! 📢 # Passed into another function: def run_op(func, val): return func(val) print(run_op(shout, "python")) # PYTHON! 🚀 ``` Remember: Parentheses `()` mean "invoke this right now." Leaving parentheses off treats the function as pure data to pass around like an integer or string. 🧠 --- ### Question What happens when you type `func` without parentheses `()` in Python? 🧠 - [ ] a. It references the function object itself instead of calling it 🎟️ - [ ] b. It raises an instant SyntaxError - [ ] c. It deletes the function from RAM 🗑️ - [ ] d. It runs the function in the background on a hidden thread 👻 --- ### Challenge Define `def add_five(x): return x + 5`. Pass `add_five` into a function `apply(func, num)` that returns `func(num)`. Print `apply(add_five, 10)`. 🎯 <details> <summary>Solution</summary> ```python def add_five(x): return x + 5 def apply(func, num): return func(num) print(apply(add_five, 10)) ``` </details>

Checkpoint

What happens when you type `func` without parentheses `()` in Python? 🧠

Practice

Define `def add_five(x): return x + 5`. Pass `add_five` into a function `apply(func, num)` that returns `func(num)`. Print `apply(add_five, 10)`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks