CHAPTER 14 · BEGINNER4 min read

Defining functions

Name a useful operation and trace how arguments enter and results leave a function call.

Python 3.12+Free to readModule 4 of 13
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Define and call a function using def, parameters, and an indented body.
  • Trace the difference between a definition and a call.
  • Write focused functions with a clear contract and a short docstring.

01Give one useful operation a name

A function packages a sequence of instructions behind a name. Use def, the function name, parentheses for parameters, and a colon, then indent the body. Defining a function creates the function object and binds its name; it does not immediately execute the body. A call with parentheses asks that function to run. This distinction lets you describe an operation once and use it in several places.

Begin with a task small enough to explain in one sentence. The greeting function below constructs and prints a welcome message for one learner. The parameter name is a local name that receives the supplied argument. When greeting('Ada') runs, the string 'Ada' becomes the value referred to by name inside that call. A later call can provide a different value without rewriting the body.

first_function.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Return a result to the caller

Printing makes information visible to a person; returning passes a value back to the calling code. A return statement ends the current call and supplies its result. The caller can store that result, print it, or use it in another expression. When a function reaches the end without returning a value, its result is None, even if it printed something along the way.

A calculation function is often more reusable when it returns the answer and lets the caller choose how to present it. In this example, the function knows how minutes convert to hours, while the final print chooses the label and display format. Keep those responsibilities clear. Later lessons develop this separation further, but you can already see how it allows one result to serve several purposes.

return_hours.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Describe the contract, not every instruction

A function's contract explains what it accepts, what it returns, and any assumptions it requires. A short docstring, written as the first string in its body, documents that purpose. It is different from a comment because Python retains it as function documentation. Make the meaning more useful than a restatement of the function's name: mention units, boundaries, or the shape of the returned data.

Choose names that describe an operation, such as total_positive_minutes, rather than an implementation detail such as loop_values. A focused function is easier to verify because you can try a small input and explain the expected output without reading unrelated work. Think about an empty collection as well as a typical collection. The accumulator pattern you already know works inside a function in exactly the same way.

documented_total.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Trace a call as a small temporary workspace

Each ordinary function call has its own local bindings. Follow the argument into the parameter, execute the body in order, and bring the returned value back to the place where the call appeared. This temporary-workspace model prevents the impression that calling a function permanently renames a variable in the caller. Parameters are names inside the function, not instructions to rewrite the caller's names.

A function can call another function, so larger operations can be built from smaller ones. Define the functions before executing the calls that need them. Resist making a new function for every individual line; group instructions around a meaningful operation. As a self-check, explain what the caller needs to know without describing the internal loop or arithmetic. A good boundary lets the caller work with the contract.

compose_operations.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • def creates a named function; a call executes its body.
  • Parameters receive arguments, and return supplies a result to the caller.
  • A focused contract and a useful docstring make a function easier to reuse and verify.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

A reusable box calculation

Define items_in_boxes(boxes, items_per_box) that returns their product. Call it for 4 boxes with 6 items each and print the result. Keep printing outside the function.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
def items_in_boxes(boxes, items_per_box):    """Return the item count for equally filled boxes."""    return boxes * items_per_boxprint(items_in_boxes(4, 6))

The function returns 24, which the caller prints. Returning keeps the calculation usable in later arithmetic as well as in a displayed message.

02

Count passing scores

Define count_passing(scores) that returns how many scores are at least 60. Use a loop, then demonstrate [55, 60, 80] and an empty list.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
def count_passing(scores):    """Return the number of scores at least 60."""    count = 0    for score in scores:        if score >= 60:            count += 1    return countprint(count_passing([55, 60, 80]))print(count_passing([]))

The outputs are 2 and 0. The return belongs after the loop so every score is considered; initializing before the loop also gives an empty input a defined result.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01When does the body of def greet(name): ... execute?
02A function prints 12 but contains no return statement. What does assigning result = that_function() store?
03Where should a function return an accumulated total when all list items must contribute?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

A reusable box calculation

Define items_in_boxes(boxes, items_per_box) that returns their product. Call it for 4 boxes with 6 items each and print the result. Keep printing outside the function.

EXPECTED OUTPUT
items_in_boxes(4 6)
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this chapter, when you want a second angle or the full details.

One chapter closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.