4.1 Defining functions

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

4.1 Defining functions

A function is a named block of code you can run whenever you need it. That keeps your program tidy and avoids repeating the same code.

Defining a function

Use def, the function name, brackets, and a colon. The code that runs when you call the function is indented:

def say_hello():
    print("Hello!")
    print("Welcome to coding club.")

Calling a function

Use the name and brackets:

say_hello()
say_hello()

Each call runs the whole block.

Parameters (inputs)

You can pass arguments into the function. The names in the brackets are parameters:

def greet(name):
    print("Hello,", name)

greet("Alex")
greet("Sam")

You can have several parameters: def add(a, b): then add(3, 5).

Return values

Use return to send a value back. The caller can use it in an expression or assign it:

def double(n):
    return n * 2

result = double(5)   # result is 10
print(double(7))    # 14

After a return, the function stops. Code below it in the same function won’t run.

Mini project: Refactor the guessing game

Take your Higher–Lower game and split it into functions, for example:

Then at the bottom: main().


Next: 4.2 Scope and return values — where variables are visible and how to use return well.