Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.10 — Designing Good Functions
Python · Example 3 of 3

Three small functions and a short script

Each function has one job and a docstring. Only the last two lines talk to the user.

A good function does one job, has a clear name and a small signature, returns its result instead of printing it, avoids changing its inputs or hidden state, and uses early returns to keep the main path flat. These habits make code easy to read, test and reuse.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

This function prints instead of returning. Rewrite it so it returns: def area(w, h): print(w * h). Use it to print area(3, 4) + 1.

02

Write normalised(numbers) that returns a new list with every number divided by the largest one, without changing the input. Show that the original list is unchanged.

03

Rewrite with guard clauses: def grade(score): returns "invalid" if score is below 0 or above 100, "pass" for 40 or more, otherwise "fail".

Explain it without notes

01

What is a pure function, and why do programmers like them?

02

Why should a function return its result instead of printing it?

03

How should a function treat a list argument it receives?

04

What is a guard clause, and how does it improve a function?

05

Give signs that a function should be split.

Three small functions and a short script
Sign in to run this example in your browser.

Expected output

{'the': 4, 'cat': 2, 'saw': 2, 'dog': 2}
('the', 4)