Nishaglobal Education logo

Functions: reusable blocks of code

Write your own Python functions with def, pass in parameters, send results back with return, use default values, and understand local variables.

Lesson 10 of 1430 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Define a function with def and call it
  • Pass values in with parameters and get a result back with return
  • Explain the difference between printing and returning
Outline
  1. What you'll learn and why it matters
  2. Defining and calling a function
  3. Parameters: giving a function information
  4. return: sending a result back
  5. Default values
  6. Variables inside functions stay inside
  7. Worked example: a grade function
  8. Practice
  9. Common mistakes
  10. Recap
  11. Quiz
  12. Mark lesson complete

What you'll learn and why it matters

You have already used many functions that come with Python: print(), len(), round(), input(). Each one does a job, and you can use it again and again without knowing how it works inside. In this lesson you write your own functions. They let you name a piece of work, reuse it, and keep long programs organised.

Defining and calling a function

Python
def greet():
    print("Hello!")
    print("Welcome to the course.")

greet()
greet()

Output

Hello!
Welcome to the course.
Hello!
Welcome to the course.
PartMeaning
defShort for “define”: you are creating a new function.
greetThe function's name. Use the same naming rules as variables.
():Brackets (empty for now) and a colon, like if and for.
The indented linesThe body: the code that runs each time the function is called.
greet()A call: it runs the body. Defining a function on its own does nothing until you call it.

Parameters: giving a function information

A parameter is a variable in the brackets that receives a value when the function is called. The value you pass in is called an argument.

Python
def greet(name):
    print(f"Hello, {name}!")

greet("Asha")
greet("Kofi")

Output

Hello, Asha!
Hello, Kofi!

When you call greet("Asha"), Python sets name = "Asha" and runs the body. A function can take several parameters, separated by commas: def area(width, height):.

return: sending a result back

Most useful functions work something out and give the answer back to the code that called them. That is what return does:

Python
def add_gst(price, percent):
    tax = price * percent / 100
    return price + tax

book = add_gst(450, 18)
pen = add_gst(90, 12)
print(book)
print(pen)
print(f"Together: {book + pen}")

Output

531.0
100.8
Together: 631.8
arguments go in450, 18def add_gst(price, percent):tax = price * percent / 100return price + taxprice = 450, percent = 18531.0return sends the result back: book = 531.0
A function is like a machine: arguments go in, the body works on them, and return sends one result back out to the line that called it.

return also ends the function immediately. Lines after a return in the same block never run.

Default values

You can give a parameter a default value. If the caller leaves it out, the default is used:

Python
def add_gst(price, percent=18):
    return price + price * percent / 100

print(add_gst(100))
print(add_gst(100, 5))

Output

118.0
105.0

Variables inside functions stay inside

Variables created inside a function are local: they exist only while the function runs. This keeps functions independent, so they do not accidentally change each other's variables.

A local variable is not visible outside
def make_total():
    total = 100
    return total

make_total()
print(total)

Python stops with this error

NameError: name 'total' is not defined

To use the result outside, store what the function returns: result = make_total().

Worked example: a grade function

Remember the grade code from lesson 6? As a function it can be reused for every student:

Python
def grade_for(marks):
    if marks >= 85:
        return "A"
    elif marks >= 70:
        return "B"
    elif marks >= 40:
        return "C"
    return "Try again"

for marks in [92, 74, 40, 12]:
    print(marks, grade_for(marks))

Output

92 A
74 B
40 C
12 Try again

Practice

Guided exercise

Average of a list

Write a function average(numbers) that returns the average of a list of numbers. Use it to print the average of [4, 8, 6] and of [10, 15].

  1. Start with def average(numbers):.
  2. Inside, return sum(numbers) / len(numbers).
  3. Call it twice inside print().
Show the solution
Solution
def average(numbers):
    return sum(numbers) / len(numbers)

print(average([4, 8, 6]))
print(average([10, 15]))

Output

6.0
12.5

How to get there: The function returns the answer instead of printing it, so the caller decides what to do with it. Here the caller prints it, but it could also store or round it.

Your turn

Temperature converter

Write to_fahrenheit(celsius) that returns celsius * 9 / 5 + 32. Use a loop to print the conversion for 0, 25 and 37 degrees Celsius.

Show the solution
Solution
def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

for c in [0, 25, 37]:
    print(f"{c}°C = {to_fahrenheit(c)}°F")

Output

0°C = 32.0°F
25°C = 77.0°F
37°C = 98.6°F

How to get there: The loop calls the function three times with different arguments. Because it returns a value, it fits neatly inside an f-string.

Common mistakes

Defining a function but never calling it

You see: Nothing happens when you run the program

Fix: Add a call such as greet() below the definition, not indented.

Calling a function before it is defined

You see: NameError: name 'greet' is not defined

Fix: Put the def above the code that calls it.

Printing instead of returning

You see: total = add(2, 3) gives None, and maths on it fails with a TypeError

Fix: Use return for values the program needs; print the returned value when you want to show it.

Wrong number of arguments

You see: TypeError: greet() missing 1 required positional argument: 'name'

Fix: Pass one argument for every parameter that has no default.

Forgetting the brackets when calling

You see: Output such as <function greet at 0x...>

Fix: Write greet() with brackets to run it.

Recap

  • def name(parameters): defines a function; name(arguments) calls it.
  • Parameters receive the values you pass in. Defaults make parameters optional.
  • return sends a result back and ends the function; print only shows it on screen.
  • Variables inside a function are local. Store the return value to use it elsewhere.

Key terms

Function
A named, reusable block of code.
Parameter / argument
A parameter is the variable in the def line; an argument is the value passed in when calling.
Return value
The result a function hands back to the code that called it.
Local variable
A variable created inside a function, which only exists while it runs.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. What does this print? def double(x): return x * 2 print(double(4) + 1)

  2. 2. What is `result` after this code? def show(x): print(x) result = show(5)

  3. 3. With `def pay(amount, tip=10):`, what is `tip` when you call `pay(500)`?

  4. 4. You define a function but nothing happens when you run the program. Why?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.