30% off your first 3 months

Get the deal

Writing your first function

by DuckyHelperNov 12, 20264 min read
Computer science

TL;DR:

  • A function packages a task under a name. Parameters are its inputs, and return hands back the result.

  • return gives a value back to the caller. print only shows text on the screen.

  • Test a function with inputs whose answers you know: radius 1 gives π, radius 0 gives 0.

Suppose you need the area of several circles: one with radius 1, another with radius 2.5, and one with radius 10. You could type 3.14159 * r * r each time. That works until you misspell it once, or change the value of π and have to find every copy. A function lets you write the idea once and use it everywhere.

The idea in plain words

A function is a named, reusable block of code. You define it once with def, and call it whenever you need it. Its parameters are the inputs it expects, written in the brackets. Its return value is the answer it gives back.

Think of it as a small machine with a label: put in a radius, and get out an area. The code inside can be as long as you like, but the caller only needs the name, the inputs, and what comes out.

Why return instead of print

print shows a value on the screen and gives nothing back to the program. return sends the value back to whoever called the function, so it can be stored in a variable, used in a calculation, or tested. A function that only prints can't be used inside other code.

Worked example: the area of a circle

The area of a circle with radius r is π × r². Python's math module provides π as math.pi, and ** raises a number to a power.

import math

def circle_area(radius):
    if radius < 0:
        raise ValueError("radius cannot be negative")
    return math.pi * radius ** 2

print(circle_area(1))
print(round(circle_area(3), 2))
  1. import math loads the module that provides math.pi.

  2. def circle_area(radius): defines a function with one parameter, radius.

  3. The if guards against nonsense input. A radius cannot be negative, so the function stops with a clear error.

  4. return math.pi * radius ** 2 computes π × r² and hands it back.

The first call prints 3.141592653589793, which is π, since π × 1² = π. The second prints 28.27: for radius 3, π × 9 = 28.2743..., and round(..., 2) keeps two decimal places.

Testing with known inputs

How do you know the function is right? Try inputs where you already know the answer.

Input

Expected

Why

0

0

Zero radius means zero area

1

π ≈ 3.14159

π × 1² = π

2

4π ≈ 12.566

π × 2² = 4π

10

about 314.16

π × 100 = 314.159...

Python can check these for you with assert, which does nothing when the condition is true and stops the program when it is false. Floating point numbers can differ in the last digits, so compare with math.isclose instead of ==.

assert circle_area(0) == 0
assert math.isclose(circle_area(1), math.pi)
assert math.isclose(circle_area(2), 4 * math.pi)
print("all tests passed")

If all three conditions hold, the program prints all tests passed. If you had written radius * 2 by mistake, circle_area(1) would give 6.28, and the second assert would fail at once, pointing you to the problem.

One function calling another

Once circle_area works, you can build on it. The volume of a cylinder is the area of its circular base times its height.

def cylinder_volume(radius, height):
    return circle_area(radius) * height

print(round(cylinder_volume(2, 5), 2))

With radius 2 and height 5 the base area is 4π and the volume is 4π × 5 = 20π ≈ 62.83. Trust in the small function is what lets you build the bigger one without redoing the circle maths.

Choosing good names and a first line of explanation

A function name should say what it does: circle_area tells you more than calc or f. Parameter names should say what they hold. A short comment or docstring on the first line helps the next reader, including you in a month.

def circle_area(radius):
    """Return the area of a circle with the given radius."""
    return math.pi * radius ** 2

The triple-quoted line is a docstring. Python stores it with the function, and tools can show it when someone asks for help on circle_area. Keep it to one clear sentence, and say what the function returns.

Variables inside a function

Names created inside a function exist only while it runs. If you define area = math.pi * radius ** 2 inside circle_area, code outside the function cannot see area. That keeps functions independent: they take their inputs through parameters and give their output through return, with nothing else leaking in or out.

How to check your answer

  • Call the function with 0, 1 and one more value you can work out on paper.

  • Check the units: if the radius is in centimetres, the area is in square centimetres.

  • Confirm it returns a value by assigning the result: a = circle_area(2).

  • Try an invalid input, such as −1, and check the error message.

Common mistakes

  • Using print where return is needed, so the caller receives None.

  • Writing radius * 2 for the square instead of radius ** 2.

  • Forgetting import math and getting a NameError.

  • Defining the function but never calling it, so nothing happens.

  • Indenting the body wrongly, which Python treats as a syntax error.

Where you will use it next

Functions are the building block for everything larger: you can call them from other functions, test them separately, and share them between programs. To keep track of your changes as the code grows, learn version control with git for beginners. The machine-level picture is in how a computer runs your code.

Frequently asked questions

Can a function have more than one parameter?

Yes. Separate them with commas, as in def area(width, height):.

What happens if a function has no return?

It returns None, Python's value for nothing.

Get started

DuckyHelper can
do more

It sees your screen and works in any app you use. Try it for 10 minutes, no card.

Get it for Mac, Windows or Linux

Share

Questions and jobs

Do anything

Ask it a question or hand it a job, in any app.

Doing jobs for you is in early access on Mac. Asking works on Mac, Windows and Linux.