Level 1: Basic Function Definition
Goal: Learn how to define simple functions with def.
def greet():
return "Hello, World!"
Concepts: Function definition, return statement, and basic usage.
Level 2: Function Arguments
Goal: Understand how to pass data to functions using arguments.
def greet(name):
return f"Hello, {name}!"
Concepts: Positional arguments, basic string formatting.
Level 3: Default Arguments
Goal: Use default argument values to make functions more flexible.
def greet(name="World"):
return f"Hello, {name}!"
Concepts: Default values, handling optional parameters.
Level 4: Variable-Length Arguments
Goal: Handle an arbitrary number of arguments using args and *kwargs.
def greet(*names):
return "Hello, " + ", ".join(names) + "!"
Concepts: args for positional arguments, *kwargs for keyword arguments.
Level 5: Return Multiple Values
Goal: Return multiple values from a function using tuples.
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
Concepts: Tuple unpacking, returning multiple values.
Level 6: First-Class Functions
Goal: Treat functions as first-class citizens by passing them as arguments or returning them.
def apply_function(func, value):
return func(value)
def square(x):
return x * x
result = apply_function(square, 5)
Concepts: Functions as arguments, higher-order functions.
Level 7: Lambda Functions
Goal: Use lambda expressions for short, unnamed functions.
def apply_function(func, value):
return func(value)
result = apply_function(lambda x: x * x, 5)
Concepts: Lambda expressions, anonymous functions.
Level 8: Decorators
Goal: Modify the behavior of functions using decorators.
def decorator(func):
def wrapper(*args, **kwargs):
print("Before the function")
result = func(*args, **kwargs)
print("After the function")
return result
return wrapper
@decorator
def greet(name):
return f"Hello, {name}!"
greet("World")
Before the function
After the function
'Hello, World!'
Concepts: Decorators, wrapping functions, modifying behavior.