๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 3 ยท Lesson 7 of 15

0% Exit to course

Module 3 ยท Reusable code and honest errors Lesson 7 of 15

Functions

Learning objective

A function is a named block you can call again. It takes inputs (parameters), does one job, and returns a result.

The concept

A function is a named block you can call again with different inputs. def average(numbers): starts the definition, the indented lines below are the body, and return hands a value back to whoever called it. Parameters are the inputs in brackets; arguments are the values you pass when you call it.

The reason to use them is not tidiness, it is change. If the average is calculated in four places and the rule changes, you edit four places and miss one. With average(marks) you edit one line. Name a function for the job โ€” clean_name, total_by_category โ€” and keep it to one job; a function that also prints, saves and emails is three functions wearing one coat.

Python
def average(numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

print(average([72, 88, 65]))   # 75.0
print(average([]))             # 0, no crash

Common mistakes

The two beginner mistakes are printing the result instead of returning it (so the caller gets None and cannot reuse it) and writing a function that depends on a variable defined outside itself. Both make the function work in the one place it was tested and fail everywhere else.

Worked example

def average(numbers): return sum(numbers) / len(numbers) โ€” then average([72, 88, 65]) works anywhere, including in a program you write next month.

Your practice task

Turn three pieces of your own code into functions and call each one twice with different values.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A function is a named block you can call again with different inputs.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.