OIM3640 - Problem Solving and Software Design

2026 Spring

Session 05 (2/3)

contain

Today's Agenda

Announcements

  • What you should have done:
    • Read and run Chapter 1 & 2 notebooks
    • Worked on Chapter 2 exercises
    • Started Learning Logs (logs/s01.md, logs/s02.md, logs/s04.md)
  • Keep pushing your work to GitHub regularly!
  • Questions?

Happy Groundhog Day!

🙋 Quick Quiz (Review S04)

  • What's the difference between int and float?
  • What does 17 % 5 return? Why?
  • What's the difference between / and //?
  • Which variable name is better and why? x vs student_count
  • What's the difference between an expression and a statement?

Chapter 3 - Functions

Why functions matter:

  • Organize your code into logical pieces
  • Reuse code without copying and pasting
  • Abstract complex operations behind simple names
  • Test pieces of your program independently

Functions are the building blocks of programs.

What is a Function?

A function is a named sequence of statements that performs a computation.

You've already used functions:

print("Hello")        # print is a function
len("Hello")          # len is a function
type(42)              # type is a function

Now you'll learn to create your own.

Anatomy of a Function

def greet(name):
    """Display a greeting message."""
    message = f"Hello, {name}!"
    print(message)
Part What it is
def Keyword that starts a function definition
greet Function name (you choose this)
name Parameter (input to the function)
"""...""" Docstring (explains what function does)
Body Indented code that runs when called

Calling Functions

Define once, use many times:

# Define the function
def greet(name):
    """Display a greeting message."""
    print(f"Hello, {name}!")

# Call it multiple times
greet("Alice")    # → Hello, Alice!
greet("Bob")      # → Hello, Bob!
greet("Class")    # → Hello, Class!

Parameters and Arguments

  • Parameter: Variable in the function definition (placeholder)
  • Argument: Actual value passed when calling
def calculate_tip(bill, percentage):  # parameters
    tip = bill * percentage / 100
    print(f"Tip: ${tip:.2f}")

calculate_tip(50, 20)  # arguments: 50 and 20

Return Values

Functions can give back a result:

def calculate_tip(bill, percentage):
    """Calculate tip amount."""
    return bill * percentage / 100

# Now we can use the result
my_tip = calculate_tip(50, 20)
print(f"Tip: ${my_tip}")

Key distinction:

  • print() → displays on screen
  • return → gives value back to caller

Functions That Return vs Print

# This RETURNS a value
def add(a, b):
    return a + b

result = add(3, 4)   # result is 7

# This PRINTS but returns None
def add_print(a, b):
    print(a + b)

result = add_print(3, 4)  # prints 7, but result is None

Most useful functions return values.

Docstrings: Documenting Functions

def calculate_bmi(weight_kg, height_m):
    """
    Calculate Body Mass Index (BMI).

    Parameters:
        weight_kg: Weight in kilograms
        height_m: Height in meters

    Returns:
        BMI value as a float
    """
    return weight_kg / (height_m ** 2)

Always write docstrings — they help you and others understand your code.

Function Design: Keep It Simple

  • Good function: Does ONE thing well
    # Good: Single purpose
    def calculate_area(width, height):
        """Calculate rectangle area."""
        return width * height
    
  • Not ideal: Does too many things and mixes responsibilities
    def process_rectangle(width, height):
        area = width * height
        print(f"Area: {area}")
        perimeter = 2 * (width + height)
        print(f"Perimeter: {perimeter}")
        # ... more stuff
    

Naming Functions Well

  • Good names describe what the function does:

    Bad Good
    do_stuff() calculate_total()
    process() validate_email()
    x() convert_to_celsius()
  • Pattern: verb_noun or verb_adjective_noun

    • get_user_input()
    • calculate_monthly_payment()
    • is_valid_email()

Scope: Where Variables Live

def my_function():
    x = 10  # x only exists inside this function
    print(x)

my_function()  # prints 10
print(x)       # ERROR! x doesn't exist here
  • Local variables: Created inside a function, die when function ends
  • Global variables: Created outside functions, accessible everywhere
  • Rule: Prefer local variables; avoid global variables when possible

📝 Your Turn

Open Chapter 3 notebook (chap03.ipynb)

Work through the examples and exercises.

Questions? Ask now!

📋 Checkpoint 1

I'll check:

  • ✅ GitHub setup: Your oim3640 repo exists and is properly structured
  • ✅ Learning Logs: You have logs for every session (s01.md, s02.md, ...)
  • ✅ Exercises: Completed exercises for Chapters 1-3

It's okay if you need more time for Chapter 3 exercises — just show progress!

Before You Leave (5 min)

  • Any questions so far?
  • Start your Learning Log for today (logs/s05.md)
  • Work on Chapter 3 exercises
  • Note down questions for next time
  • Push your work to GitHub

Next session: Functions and Interfaces (Chapter 4)

global styles