Functions – Defining, online

Six activities your students do on their own devices. See who's finished, and their scores.

Functions – Defining in one minute

What students need to know

A function is a reusable, named block of code, created with the def keyword: def greet():. The indented lines underneath — the function body — only run when the function is called by writing its name followed by parentheses: greet(). Defining a function doesn't run it; nothing happens until it's actually called, which is what lets the same code run many times from different places in a program.

Mistakes students make

  • Forgetting the colon at the end of the def line (def greet() instead of def greet():) is the most common error.
  • Another is defining a function but forgetting to call it — the code inside never runs on its own.

Discover other journeys with this module

What students will learn in this module

Every question in Module 24

Quick questions

  1. What does def do?ADefines a new functionBDeletes a function
  2. How do you call a function named greet?Agreet()Bdef greet()
  3. def say_hi():\n print('Hi')\nDoes this print anything?AYes prints HiBNo defining doesn't run it
  4. What goes at the end of a def line?AA semicolon ;BA colon :
  5. Why use functions?ATo reuse code without rewriting itBTo make code slower

Key terms

Students type the meaning of:

  • def
  • Function
  • Call
  • Function body

Match the pairs

def greet()
    print('Hi')
Match it to what it does
Def say_hi():
    print('Hi')
Match it to what it does
def greet():
    print('Hello')
Match it to what it does
def greet():
    print('Hi')
greet()
Match it to what it does
def say_hi():
    print('Hi!')
say_hi()
Match it to what it does
def say_hi():
    print('Hi!')
Match it to what it does

Fill in the blanks

  1. ___ greet():
        print('Hello!')
  2. def greet()_
        print('Hello!')
  3. def greet():
        print('Hello!')
    
    _____()
  4. def say_hi():
        print('Hi!')
    
    ______()
  5. def welcome():
        print('Welcome!')
    
    _______()

Spot the error

Question 1

Adef greet()B    name = 'World'C    print('Hello, ' + name)D    print('Goodbye!')Egreet()

Question 2

Adef greet():B    name = 'World'Cprint('Hello, ' + name)D    print('Goodbye!')Egreet()

Question 3

ADef greet():B    name = 'World'C    print('Hello, ' + name)D    print('Goodbye!')Egreet()

Question 4

Adef greet:B    name = 'World'C    print('Hello, ' + name)D    print('Goodbye!')Egreet()

Question 5

Adef greet():B    print('Hello!')CDdef greet()