← All lessons
Programming basics · Lesson 6 of 9

Functions

A function is a named set of steps you can use again. You've used some already: print(), len(), int(). With def you make your own. The indented lines under def are the function's body; they don't run until the function is called.

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

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

The names in the brackets of def are parameters: when you call greet("Ana"), the parameter name holds "Ana" for that call. The value you pass in is called an argument.

return sends a value back to whoever called the function, and the function stops there. Printing and returning are different: a function that only prints shows something on screen, but you can't use its result in a sum. A function without a return gives back None.

def area(width, height):
    return width * height

print(area(3, 4) + area(2, 5))
Prints
22

Variables made inside a function belong to it (they're local) and disappear when it returns, so two functions can each have their own total without clashing. Small functions with clear names make a program much easier to read and to fix.

Practice

What does this print?

def double(n):
    return n * 2

print(double(double(3)))
More info

Quick reference

def name(params):Defines a function. The body is indented.
return valueSends the value back and ends the function.
name(args)Calls the function.
NoneWhat a function gives back when it has no return.

The other computer science courses