Unit 06 · lesson

Building Your First Functions

Core path: 30 minutes

Why create a function when copy and paste already works?

Start with the ugly version.

print("====================")
print("SYSTEM STATUS")
print("====================")
print("Battery: 82%")

print("====================")
print("SYSTEM STATUS")
print("====================")
print("Temperature: 71.4")

print("====================")
print("SYSTEM STATUS")
print("====================")
print("Network: ONLINE")

The program runs.

Now the heading needs to change from SYSTEM STATUS to ROBOT STATUS.

How many places do you have to edit?

That repeated responsibility is the problem functions can solve.

You have been calling functions since Week 1

These should look familiar:

print("Hello")
input("Name: ")
int("42")
type(42)
range(5)

Somebody already defined those behaviors. You have been calling them.

This week you start defining behavior yourself.

Define once, call when needed

def show_header():
    print("====================")
    print("SYSTEM STATUS")
    print("====================")

Run the file exactly like that.

Nothing visible happens.

That is correct.

Python encountered the def statement and created the function definition. It did not automatically execute the body.

Now add:

show_header()

The call tells Python to execute the function body.

This distinction is the first important function mental model:

DEFINITION
what behavior exists

CALL
execute that behavior now

A file can contain ten perfectly valid function definitions and still appear to do nothing if no code ever calls them.

Follow control into the function and back out

Consider:

def show_header():
    print("--- STATUS ---")

print("Before")
show_header()
print("After")

Execution is conceptually:

print("Before")

call show_header()

enter function body

print("--- STATUS ---")

function finishes

return control to caller

print("After")

Expected output:

Before
--- STATUS ---
After

That return to the caller happens even when the function does not explicitly return a useful value. Execution still has to continue from the place that called it.

Read the syntax as structure

def greet():
    print("Hello, developer.")

The pieces are:

def        define a function
 greet      function name
()          parameter list — empty for now
:           begins the function block
indentation function body

Do not obsess over memorizing the anatomy diagram. Type a few functions and the punctuation becomes familiar.

The real question is what responsibility the function name represents.

Functions are not only about avoiding repetition

Repeated code is an easy reason to introduce a function, but it is not the only reason.

A function can make a program easier to understand by naming a job:

determine_status()
calculate_average()
show_menu()
load_players()

Compare that with reading the entire implementation every time you want to know what that section of code is trying to accomplish.

A good function gives another developer a useful boundary.

Refactor without changing behavior

Before:

print("--- STATUS ---")
print("Battery: 82")
print("--- STATUS ---")

After:

def show_status_header():
    print("--- STATUS ---")

show_status_header()
print("Battery: 82")
show_status_header()

Run both versions.

The visible output should match.

You changed the structure of the program without intentionally changing its external behavior.

That is a small refactor.

If the output changes unexpectedly, do not congratulate yourself on the cleaner architecture yet. Investigate the regression.

A function name should explain the job

These names communicate actions:

def show_menu():
    ...


def calculate_score():
    ...


def check_battery():
    ...

These make the reader decode your intent:

def stuff():
    ...


def do_it():
    ...

The same naming rule from variables applies here, but function names usually describe behavior rather than stored state.

Do not create a function for every line

This is technically possible:

def print_equals():
    print("====================")

That does not automatically make the program better.

A useful function usually represents a coherent responsibility another developer can name and reason about.

More functions can create more fragmentation if the boundaries are meaningless.

Extract one responsibility from a larger script

Start with:

print("=== PLAYER ===")
print("Name: Nova")
print("Score: 850")
print()
print("=== PLAYER ===")
print("Name: Maya")
print("Score: 960")

What repeats?

The heading behavior.

A first refactor:

def show_player_header():
    print("=== PLAYER ===")


show_player_header()
print("Name: Nova")
print("Score: 850")
print()

show_player_header()
print("Name: Maya")
print("Score: 960")

That still does not solve the repeated player data display. Good. We do not have to solve the whole architecture in one jump.

Lesson 2 adds parameters so a function can work with changing data.

Before moving on

You should be able to explain:

  • the difference between defining and calling a function;
  • where execution goes during a function call;
  • why a function body is indented;
  • one reason besides repetition to create a function; and
  • why more functions do not automatically mean better design.

Vocabulary lab

Flip the idea, not just the card

Explain the term before you reveal the back. Then compare your explanation with the definition, example, and warning.

1 / 5
Read all terms without animation
Function
A named block of behavior that can be called from another part of a Python program. Example: show_header() executes the behavior defined under def show_header(). Do not confuse it with: A loop whose primary job is repetition control.
Function Definition
The def statement and body that create a function's behavior. Example: def greet(): creates the function greet. Do not confuse it with: A function call that executes the defined behavior.
Function Call
An instruction that transfers execution into a function and then returns control to the caller when the function finishes. Example: greet() calls the greet function. Do not confuse it with: The def statement that defines the function.
Function Body
The indented statements that execute when a function is called. Example: The print statement indented beneath def greet(). Do not confuse it with: Code outside the function after the call.
Refactoring
Changing code structure without intentionally changing the behavior users or callers depend on. Example: Replacing repeated header statements with show_header(). Do not confuse it with: Adding a new feature that changes required behavior.