Defining Functions and Arguments
Create custom functions using def, handle positional and keyword arguments, and work with return values.
Learning objectives
- Define functions using the def keyword
- Use positional, default, and keyword arguments
- Understand variable scope (LEGB rule: Local, Enclosing, Global, Built-in)
Lesson material
Function Definition
Functions encapsulate logic into callable blocks.
Example code
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", greeting="Welcome"))
Practice exercise: Multiply Function
Define a function `multiply(a, b=2)` that returns the product of `a` and `b`. Print `multiply(5)` and `multiply(5, 4)`.