Part 3 of 6 · Chapter 3 of 4

Naming a Piece of Work

Copy the same five lines into three places in a program and you have created three bugs waiting to happen, not three features. Wrap them in a function once, and watch every copy become a single name you can call.

Beginner10 min read

Copy the same five lines into three places in a program and you have created three bugs waiting to happen, not three features. Wrap them in a function once, and watch every copy become a single name you can call.

Naming a piece of work you will repeat

greet.py
def greet(name):    print(f"Hello, {name}!") greet("Ada")greet("Grace")

def defines the function once. Every line after it that calls greet(...) reuses that same definition — fix a bug inside greet, and every call to it is fixed, everywhere, in one edit.

def square(x):

x =

square(x)

return x * x

returns

16

Change xabove, and only the input to the machine changes. The function's own definition — the middle box — never moves. That is what naming a piece of work buys you: change the input, run the same code, get the answer for that input.

Parameters are just names local to the call

name inside greet is a name that exists only while that particular call is running. Each call gets its own — calling greet("Ada") and greet("Grace") back to back does not leave name holding "Ada" by the time the second call starts.

Return sends a value back; print only ever shows you one

print writes text to the screen and hands nothing back to the rest of the program. return sends a value back to wherever the function was called from, so it can be stored, compared, or passed to something else.

Terminal
$ >>> def add(a, b):$ ...     return a + b$ ...$ >>> result = add(3, 4)$ >>> result$ 7

Key takeaways

  • A function names a piece of work once. Every call reuses that same definition.
  • Parameters are local to each call — one call's values never leak into another's.
  • print shows you something on screen and returns nothing to the program. return hands a value back.
  • A function with no return statement returns None, whether or not it printed something along the way.