Lesson 8 of 15
Functions
Functions
Functions are first-class objects in Python — they can be passed as arguments, returned from other functions, and stored in variables.
def and return
def add(a, b):
return a + b
result = add(3, 4) # 7
Default Arguments
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Bob", "Hi") # "Hi, Bob!"
*args and **kwargs
def total(*args): # collects positional args into tuple
return sum(args)
def info(**kwargs): # collects keyword args into dict
for k, v in kwargs.items():
print(f"{k}: {v}")
total(1, 2, 3) # 6
info(name="Alice", age=30)
Functions as Arguments
def apply(f, x):
return f(x)
apply(abs, -5) # 5
apply(str.upper, "hi") # "HI"
Lambda
double = lambda x: x * 2
double(4) # 8
Your Task
Implement apply_twice(f, x) that applies function f to x twice: f(f(x)).
Pyodide loading...
Loading...
Click "Run" to execute your code.