Functions
Learn how to write reusable code with functions.
What are Functions?
Functions are reusable blocks of code that perform specific tasks.
def greet(name):
"""Say hello to someone"""
return f"Hello, {name}!"
# Call the function
message = greet("Alice")
print(message) # Hello, Alice!
Function Parameters
Positional Parameters
def add(a, b):
return a + b
result = add(5, 3) # 8
Keyword Arguments
def introduce(name, age, city):
return f"{name} is {age} years old from {city}"
# Can specify arguments by name
intro = introduce(name="Bob", city="NYC", age=30)
Default Parameters
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (5^2)
print(power(5, 3)) # 125 (5^3)
Variable Arguments
def sum_all(*numbers):
"""Sum any number of arguments"""
return sum(numbers)
print(sum_all(1, 2, 3)) # 6
print(sum_all(10, 20, 30, 40)) # 100
Return Values
# Single return
def double(x):
return x * 2
# Multiple returns
def min_max(numbers):
return min(numbers), max(numbers)
smallest, largest = min_max([1, 5, 3, 9, 2])
Lambda Functions
# Anonymous functions
square = lambda x: x ** 2
print(square(5)) # 25
# Useful with map, filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
Scope
# Global scope
global_var = "I'm global"
def my_function():
# Local scope
local_var = "I'm local"
print(global_var) # Can access global
my_function()
# print(local_var) # Error! Can't access local
Best Practices
- Use descriptive names -
calculate_total()notcalc() - Single responsibility - One function, one task
- Document with docstrings - Explain what it does
- Keep it short - Under 20 lines ideally
- Return early - Handle edge cases first
Practice
Write a function that: 1. Takes a list of numbers 2. Returns average, minimum, and maximum 3. Handles empty list gracefully
def analyze_numbers(numbers):
# Your code here
pass
Happy coding! 🚀