logo
28

Function Basics

⏱️ 35 min

Functions: Package Repeated Logic into Reusable Units

What You Might Be Wondering

"I can just keep writing code top to bottom. Why bother with functions?"

Because functions make code reusable, testable, and maintainable. Without them, any project bigger than a script will fall apart.

One-Line Definition

A function is a named block of logic that takes input and returns output.

Real-Life Analogy

Like a premade sauce recipe in a kitchen: write it once, use it whenever you need it. No starting from scratch every time.

Minimal Working Example

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Parameters & Default Values

def add(a, b=0):
    return a + b

print(add(2, 3))
print(add(5))

Returning Multiple Values

def min_max(nums):
    return min(nums), max(nums)

mn, mx = min_max([3, 8, 1, 6])
print(mn, mx)

Design Tips (Beginner Edition)

  • One function, one job
  • Name it after what it does, not how it does it
  • Clear inputs and outputs — minimize hidden dependencies

Quick Quiz (5 min)

  1. Write calc_tax(amount, rate=0.1).
  2. Write a function that calculates the average of a list (handle empty lists).
  3. Write a function that checks if a string is a palindrome.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Break an "input -> calculate -> output" monolith script into 3 functions and compose them.

Acceptance Criteria

You can independently:

  • Define and call functions
  • Use parameters and return values correctly
  • Extract repeated logic into functions

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: one function that does everything.

  • Reality: keep it single-responsibility.

  • Misconception: using a mutable object (like []) as a default parameter.

  • Reality: default parameters should be immutable values. Mutable defaults are shared across calls — that's a classic Python gotcha.