Function Basics
Functions are reusable blocks of code defined with the def keyword.
Defining Functions:
def function_name(parameters):
Parameters:
- Required parameters: must be provided
- Default parameters: have default values
- *args: variable positional arguments
- **kwargs: variable keyword arguments
Return Values:
- Use return to send back a value
- Functions return None by default
- Can return multiple values (tuple)
Docstrings: Document your functions with triple quotes.
Scope:
- Local: defined inside function
- Global: defined outside function
- Use global keyword to modify global variables
Code Examples
Python Functionspython
# Basic function
def greet(name):
"""Greet a person by name."""
return f"Hello, {name}!"
print(greet("Alice"))
# Default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
print(greet_with_title("Smith"))
print(greet_with_title("Smith", "Dr."))
# Multiple return values
def get_stats(numbers):
"""Return min, max, and average."""
return min(numbers), max(numbers), sum(numbers)/len(numbers)
minimum, maximum, average = get_stats([1, 2, 3, 4, 5])
print(f"Min: {minimum}, Max: {maximum}, Avg: {average}")
# *args - variable arguments
def sum_all(*numbers):
return sum(numbers)
print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")
# **kwargs - keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="NYC")
# Lambda functions
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")
# Lambda with sorted
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
sorted_by_age = sorted(people, key=lambda p: p[1])
print(f"Sorted: {sorted_by_age}")Python functions are flexible with *args and **kwargs allowing variable numbers of arguments.
Quick Quiz
1. What does **kwargs allow you to do?
Was this lesson helpful?