Lessons / Python / Unit 4

Functions

A function is a named piece of code you can run again and again. In Python you make one with def.

Python · Unit 4 of 5 · about 4 minutes

Making and calling a function

Write def, a name, brackets and a colon. The indented lines underneath are the function's body. They run when you call the function.

def say_hi():
    print("Hi!")

say_hi()
say_hi()
Hi!
Hi!

Arguments

Names inside the brackets are parameters. When you call the function, the values you pass in, called arguments, get stored in them.

def greet(name):
    print("Hi, " + name)

greet("Sam")
greet("Ana")
Hi, Sam
Hi, Ana

return

return sends a value back to where the function was called. The function stops as soon as it returns.

def double(n):
    return n * 2

print(double(4) + 1)
9

Try it

What does this print?

def square(n):
    return n * n

print(square(3) + square(1))
square(3) is 9 and square(1) is 1. 9 + 1 is 10.

Default values

A parameter can have a default. If the caller leaves it out, the default is used.

def greet(name="friend"):
    return "Hi, " + name

print(greet())
print(greet("Sam"))
Hi, friend
Hi, Sam

Try it

What does this print?

def welcome(place="home"):
    return "Welcome " + place

print(welcome("back"))
An argument was passed in, so it replaces the default.

Printing is not returning

If a function prints a value but doesn't return it, you get None back. None is Python's way of saying "nothing".

def add(a, b):
    print(a + b)

result = add(2, 3)
print(result)
5
None

Try it

In the add example, what is stored in result?

add prints 5 but has no return line, so calling it gives back None.

Common mistakes

Calling a function before it's defined

Python reads top to bottom. If you call greet() above the def greet line, you get a NameError.

Forgetting the brackets

say_hi on its own doesn't run anything. You need say_hi().

Forgetting return

A function that calculates a value but doesn't return it gives back None.

Recap

  • def makes a function. Its body is indented.
  • Parameters receive the arguments you pass in.
  • return sends a value back and ends the function.
  • No return means the function gives back None.