Python Chapter 4: Functions

Master the art of writing reusable, modular code with Python functions

Understanding Python Functions

What is a Function?
A function is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and make programs more modular and maintainable.

1. Defining Functions

Functions are defined using the def keyword:

def greet(): """This is a docstring - it describes what the function does.""" print("Hello, World!") # Calling the function greet() # Output: Hello, World!

2. Parameters vs Arguments

Parameters

Variables listed in the function definition

def greet(name): # 'name' is a parameter print(f"Hello, {name}!")

Arguments

Actual values passed when calling the function

greet("Alice") # 'Alice' is an argument # Output: Hello, Alice!

3. Return Values

Functions can return values using the return statement:

def add(a, b): """Returns the sum of two numbers.""" return a + b result = add(5, 3) print(result) # Output: 8

4. Default Parameters

Parameters can have default values:

def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Bob")) # Output: Hello, Bob! print(greet("Bob", "Hi")) # Output: Hi, Bob!

5. Docstrings

Document your functions with triple-quoted strings:

def calculate_area(radius): """ Calculate the area of a circle. Args: radius (float): The radius of the circle Returns: float: The area of the circle """ return 3.14159 * radius ** 2

Interactive Function Builder

Create and test your own Python functions!

Generated Function:

Your function will appear here...

Variable Scope Visualizer

Scope Rules:
Local Scope: Variables defined inside a function
Global Scope: Variables defined outside all functions
LEGB Rule: Local → Enclosing → Global → Built-in

Example Code:

x = 10 # Global variable def outer_function(): y = 20 # Enclosing scope def inner_function(): z = 30 # Local scope print(f"x={x}, y={y}, z={z}") inner_function() outer_function()

Scope Visualization:

Interactive Scope Tester

Call Stack Visualizer

Recursion: A function that calls itself. Each recursive call is added to the call stack until a base case is reached.

Factorial Example:

def factorial(n): """Calculate factorial recursively.""" if n <= 1: # Base case return 1 return n * factorial(n - 1) # Recursive case

Call Stack (Bottom to Top):

Click "Animate Call Stack" to see the visualization

Parameter Playground

Positional Arguments

def greet(first, last): return f"Hi {first} {last}" print(greet("John", "Doe")) # Output: Hi John Doe

Keyword Arguments

def greet(first, last): return f"Hi {first} {last}" print(greet(last="Doe", first="John")) # Output: Hi John Doe

Default Parameters

def power(base, exp=2): return base ** exp print(power(3)) # 9 print(power(3, 3)) # 27

*args (Variable Positional)

def sum_all(*args): return sum(args) print(sum_all(1, 2, 3, 4, 5)) # Output: 15

**kwargs (Variable Keyword)

def print_info(**kwargs): for key, val in kwargs.items(): print(f"{key}: {val}") print_info(name="Alice", age=30)

Mixed Parameters

def func(pos, *args, key=0, **kwargs): return (pos, args, key, kwargs) print(func(1, 2, 3, key=4, x=5)) # (1, (2, 3), 4, {'x': 5})

Custom Parameter Test

Advanced Function Concepts

1. Lambda Functions (Anonymous Functions)

Short, one-line functions without a name:

# Regular function def square(x): return x ** 2 # Lambda equivalent square = lambda x: x ** 2 print(square(5)) # Output: 25 # Common use with map, filter, sorted numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, numbers)) print(squared) # [1, 4, 9, 16, 25]

2. First-Class Functions

Functions are objects - they can be assigned, passed as arguments, and returned:

def shout(text): return text.upper() def whisper(text): return text.lower() def apply_formatter(func, text): """Apply a formatting function to text.""" return func(text) print(apply_formatter(shout, "hello")) # HELLO print(apply_formatter(whisper, "HELLO")) # hello

3. Closures

Functions that remember values from their enclosing scope:

def make_multiplier(n): """Returns a function that multiplies by n.""" def multiplier(x): return x * n return multiplier times_3 = make_multiplier(3) times_5 = make_multiplier(5) print(times_3(10)) # 30 print(times_5(10)) # 50

4. Decorators (Preview)

Functions that modify other functions:

def uppercase_decorator(func): def wrapper(): result = func() return result.upper() return wrapper @uppercase_decorator def greet(): return "hello" print(greet()) # HELLO

Test Your Knowledge

Answer all questions and click "Submit Quiz" to see your score!

Course Home