Chapter 6: Functions in Python – Reusable Code Blocks

Previous Chapter Table of Contents Next Chapter

1. Function Fundamentals

Function Structure Diagram

Anatomy of a Python function

Defining and Calling Functions

# Function definition
def greet(name):
    """Returns a greeting message"""
    return f"Hello, {name}!"

# Function call
message = greet("Alice")
print(message)  # Output: Hello, Alice!

Exercise 1: Temperature Converter

Create a function that:

  1. Converts Fahrenheit to Celsius
  2. Formula: C = (F - 32) × 5/9
  3. Test with 68°F (should return 20°C)

2. Parameters & Arguments

Type Description Example
Positional Matched by position func(1, 2)
Keyword Matched by name func(a=1, b=2)
Default Optional parameters def func(a=0)

Example: Flexible Arguments

def describe_pet(pet_name, animal_type="dog"):
    print(f"I have a {animal_type} named {pet_name}")

# Different calling styles
describe_pet("Rover")
describe_pet("Fluffy", "cat")
describe_pet(animal_type="hamster", pet_name="Harry")

Output

I have a dog named Rover
I have a cat named Fluffy
I have a hamster named Harry

3. Return Values

Function Flow Diagram

How data flows through functions

def calculate_stats(numbers):
    """Returns tuple of (min, max, avg)"""
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

stats = calculate_stats([10, 20, 30])
print(stats)  # (10, 30, 20.0)

Exercise 2: Password Validator

Create a function that:

  1. Takes a password string
  2. Returns True if length ≥ 8 and contains a digit
  3. Returns False otherwise

4. Variable Scope

Global vs Local

count = 10  # Global variable

def increment():
    count = 5  # Local variable
    return count + 1

print(increment())  # 6
print(count)        # 10 (global unchanged)

Using global

total = 0

def add_to_total(n):
    global total
    total += n

add_to_total(5)
print(total)  # 5

Previous Chapter Contents Next Chapter