Introduction
Functions are reusable blocks of code that perform a specific task.
Defining Functions
def greet(name):
"""Greet a person by name."""
return f"Hello, {name}!"
# Default parameters
def power(base, exponent=2):
return base ** exponent
# Multiple return values
def solve(a, b):
sum_ = a + b
product = a * b
return sum_, product
Args and Kwargs
def flexible(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
flexible(1, 2, name="John", age=25)
Practice Problems
- Create a function to check prime numbers
- Implement a Fibonacci sequence generator
- Build a calculator with multiple operations
- Create a function that accepts variable arguments
- Write a decorator to measure function execution time