Codiqo

Learn Python · lesson 33 of 60 · about 7 minutes

Defining Functions and Parameters

Give the assistant its first function: one show() that prints any list with a heading, for the shopping and the to-do list.

What you'll learn

  • Define a function with def
  • Call a function
  • Pass values in with parameters

The same job twice

Sam's assistant prints the shopping list one way and the to-do list another, and every new list would need its own loop. A function packs that job into one named block: def show(title, items): prints a heading and numbers the items, and calling show("Shopping", shopping) or show("To-do", todo) runs it for whichever list you hand it.

Name a piece of code

A function is a named block of code you can run whenever you like. def defines it; writing its name with brackets calls it.

Defining a function doesn't run it. Nothing happens until you call it.

Define once, call twice

def cheer():
    print("Go Phoebe!")

cheer()
cheer()

Output

Go Phoebe!
Go Phoebe!

Parameters

Parameters are names in the brackets that receive values when you call the function. The values you pass in are called arguments.

Greeting anyone

def greet(name, times):
    for _ in range(times):
        print(f"Hi, {name}!")

greet("Ada", 2)
greet("Bo", 1)

Output

Hi, Ada!
Hi, Ada!
Hi, Bo!

Tip

Functions let you write something once and reuse it. If you find yourself copying and pasting code, that's a sign it wants to be a function.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.