CodingNic

Functions

Module Overview

Functions 5 min read

Module Overview

Functions

Every program so far in this course has run top to bottom, once. This module introduces functions: a way to package up code so you can run it again and again, with different input each time.

Why This Matters

Without functions, any change to what you want to compute means rewriting the whole thing. For example, without a function, printing a greeting for three different people means writing the same print() line three times, changing only the name. A function lets you write that logic once and reuse it:

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

greet("Erin")
greet("Jordan")
greet("Maya")

Run it, and Python prints:

text
Hello, Erin!
Hello, Jordan!
Hello, Maya!

That’s the whole point of this module: write something once, then reuse it with different input instead of copying and changing code by hand.

What You’ll Learn

  • How to define a function and return a value from it
  • How to accept arguments, set defaults, and handle an unknown number of inputs
  • What scope means, and what a function can and can’t see outside itself
  • How to document a function with docstrings and type hints
  • How to write a recursive function (one that calls itself)

Outcome

By the end of this module, you’ll be able to write your own functions, with flexible arguments, sensible defaults, and clear documentation, instead of repeating the same code with small changes. The module closes with a mini project: a command-line quiz game built from everything covered here.

Let’s get started.