Introduction
Functions are the building blocks of reusable code. Python functions are defined with the def keyword and support powerful features like default arguments, keyword arguments, and more.
Defining functions
def greet(name):
"""Greet someone by name."""
return f"Hello, {name}!"
print(greet("Alice")) # "Hello, Alice!"
# Default parameters
def power(base, exponent=2):
return base ** exponent
power(3) # 9
power(3, 3) # 27
# *args and **kwargs
def flexible(*args, **kwargs):
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
flexible(1, 2, 3, name="Alice", age=30)
# Args: (1, 2, 3)
# Kwargs: {'name': 'Alice', 'age': 30}
# Lambda functions (anonymous)
square = lambda x: x ** 2
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers, key=lambda x: -x) # [5, 4, 3, 1, 1]Docstrings
Always document your functions with docstrings. They describe what a function does and can be accessed via help().
def calculate_area(radius):
"""Calculate the area of a circle.
Args:
radius: The radius of the circle.
Returns:
The area as a float.
"""
import math
return math.pi * radius ** 2Assignment
- Read about defining functions.
- Write a function that takes a list and returns a new list with duplicates removed (preserving order).
- Practice using
*argsand**kwargs.