All lessons

Functions & collections · step 16 of 22

Functions

11 minName a block of code, give it inputs and get a value back.

Name a block of code

A function packages code you want to reuse. def defines it and you choose the inputs, called parameters.

def greet(name):
    return "Hello, " + name + "!"

print(greet("Ada"))     # Hello, Ada!

Nothing runs when you define a function — it runs when you call it.

return vs print

print shows a value to a human. return hands the value back to the code that called the function, so it can be stored or reused. A function without a return gives back None.

def double(number):
    return number * 2

total = double(21)
print(total)     # 42

Being able to store the result is the whole point: double(21) can be part of a bigger calculation, while a printed line cannot.

Defaults and imports

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Grace"))                 # Hello, Grace!
print(greet("Ada", greeting="Hey"))   # Hey, Ada!

Functions are also how you use other people's code: import random then random.randint(1, 6), or from math import sqrt then sqrt(16).

Remember this

  • def defines a function, calling it runs it
  • return gives a value back, print only shows it
  • Parameters are inputs; defaults make them optional

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. Which word sends a value back from a function?

  2. 2. What does a function return if it has no return statement?

  3. 3. In `def add(a, b):` what are a and b?

Answer all three to check them.

Now write it yourself

0/3 passed
1

Practice 1

Write a function `double(number)` that returns the number multiplied by 2.

practice_1.py
2

Practice 2

Write a function `greet(name)` that returns a greeting like `Hello, Ada!`

practice_2.py
3

Practice 3

Write a function `area(width, height)` that returns width multiplied by height.

practice_3.py

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.