Learn

Short lessons with real code you can edit and run on the page.

Functions in Python

Lesson 22 Python 3.14 Runs in your browser Updated
In short

A function is a named block of code that runs only when you call it. You define one with def, give it parameters for the values it needs, and send a result back with return. A function without a return statement gives back None.

Key facts

  • def greet(): followed by an indented block defines a function named greet, and greet() calls it.
  • Parameters are the names in the def line. Arguments are the values passed in the call.
  • return sends a value back to the caller and ends the function at once.
  • A function with no return statement returns None.
  • The def must run before the first call, or Python raises NameError.

What is a function in Python?

A function is a named block of code that runs only when you call it. You write the code once, give it a name, and run it from anywhere later in the program by writing that name followed by parentheses.

Python
def greet():
    print("Hello!")
    print("Welcome to Python.")

greet()
greet()
Output
Hello!
Welcome to Python.
Hello!
Welcome to Python.

The def block on its own prints nothing. Python stores the function under the name greet and moves on, so the output only appears at the two calls at the bottom. You have been calling functions since the first lesson, because print(), len() and input() are functions too.

Functions that work without any import, like those three, are called built-in functions, and the ones you write are user-defined. Writing your own keeps a program short, because code used in several places lives in one function, and a fix to it applies everywhere.

How do I define and call a function in Python?

Define the function with def, then call it by name with parentheses. The definition has to come first, because Python runs a file from top to bottom.

  1. Write the def line. Start with def, then the function's name, a pair of parentheses and a colon, as in def show_line():. Function names follow the rules for variable names and, by convention, are written in lowercase with underscores between words.
  2. Indent the body. Indent every line of the body, usually by four spaces. The first line that isn't indented is outside the function.
  3. Call the function. Write its name with parentheses, such as show_line(), on a line below the definition. Each call runs the body again from the top.
Python
def show_line():
    print("-" * 20)

show_line()
print("Report")
show_line()
Output
--------------------
Report
--------------------

The two calls print the same row of dashes above and below Report. Changing "-" * 20 in the function changes both rows.

What is the difference between a parameter and an argument?

A parameter is a name in the def line, and an argument is the value you pass in the call. While the function runs, each parameter holds its argument, like a variable that exists only inside the function.

Python
def greet(name):
    print(f"Hello, {name}!")

greet("Ada")
greet("Grace")
Output
Hello, Ada!
Hello, Grace!

Here name is the parameter, and "Ada" and "Grace" are the arguments. A function can have several parameters separated by commas, and the arguments fill them in order. The function arguments lesson covers default values and passing arguments by name.

What does return do in a Python function?

return sends a value back to the code that called the function and ends the function at once. The call then stands for that value, so you can store it, print it or use it in a calculation.

Python
def add(a, b):
    return a + b

total = add(2, 3)
print(total)
print(add(10, 5) * 2)
Output
5
30

add(2, 3) runs the body with a set to 2 and b set to 3, and the call gives back 5, which is stored in total. In the last line, the returned 15 is doubled before print() receives it.

Because return ends the function, a function can have several return statements, and only the first one Python reaches runs.

Python
def sign(n):
    if n > 0:
        return "positive"
    if n < 0:
        return "negative"
    return "zero"

print(sign(5))
print(sign(-2))
print(sign(0))
Output
positive
negative
zero

When n is 5, the first return runs and the function stops there, so the later checks never happen and sign() needs no elif or else.

A return inside a loop ends the loop and the function together. Inside nested loops it leaves all of them at once, which break can't do, as the break and continue lesson showed.

Python
def first_negative(numbers):
    for n in numbers:
        if n < 0:
            return n
    return None

print(first_negative([4, 7, -2, 9, -5]))
print(first_negative([1, 2, 3]))
Output
-2
None

The last line of the function runs only when no number is negative. return None could be left out, because a function that reaches its end returns None anyway, but writing it makes the not-found result clear.

What is the difference between return and print in Python?

return hands a value back to the program, and print() only shows it on the screen. A function that prints without returning gives the caller None, Python's value for nothing.

Python
def show_double(n):
    print(n * 2)

def double(n):
    return n * 2

result = show_double(4)
print(result)
result = double(4)
print(result)
Output
8
None
8

show_double(4) prints 8 from inside the function, but result gets None, because the function has no return statement. double(4) prints nothing itself, and its 8 appears only because the program printed the returned value.

Python return compared with print()
Questionreturnprint()
What is it?A statement that ends the functionA built-in function
Where does the value go?Back to the code that made the callTo the screen
Can the program use the value?Yes, it can store it or calculate with itNo, it only becomes text on the screen
Does the function keep running?No, it stops at onceYes, the next line runs
Use it whenOther code needs the resultA person needs to see the value

Most functions should return their result and leave the printing to the code that calls them, which can then print it, store it or pass it to another function.

Can a Python function return more than one value?

Yes. Write the values after return separated by commas, and Python returns them together as one tuple. Unpack the tuple into separate variables at the call, the way the tuples lesson unpacks a point.

Python
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([4, 1, 9, 7])
print(low, high)
print(min_max([4, 1, 9, 7]))
Output
1 9
(1, 9)

The first call unpacks the tuple into low and high. The second prints the tuple itself, which shows that the function returned a single tuple holding two values.

How do I write a docstring for a function?

Put a string in triple quotes on the first line of the function's body. That string is the docstring, and it says what the function does.

Python
def celsius_to_fahrenheit(celsius):
    """Convert a temperature from Celsius to Fahrenheit."""
    return celsius * 9 / 5 + 32

print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit.__doc__)
Output
212.0
Convert a temperature from Celsius to Fahrenheit.

Python stores the docstring in the function's __doc__ attribute, a value attached to the function and read with a dot. help(celsius_to_fahrenheit) prints it along with the parameter list.

PEP 257, the docstring style guide, recommends writing it as a command, such as "Convert..." or "Return...". The comments lesson compares docstrings with # comments.

Common mistakes with functions in Python

These four mistakes come up most with functions. The last one is the hardest to spot, because the program runs without any message.

  • NameError: name 'say_hi' is not defined. The call runs before the def, or the name is misspelled. Move the definition above the first call.
  • TypeError: greet() missing 1 required positional argument: 'name'. The call passed fewer arguments than the function has parameters. Pass one value for each parameter.
  • TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. The function printed its result instead of returning it, so the call gave back None. Change print() to return.
  • Forgetting the parentheses. greet without parentheses refers to the function but doesn't call it, so nothing runs. print(greet) shows something like <function greet at 0x...> instead of a result.

Run the three broken programs to see the messages, then fix each one in the editor. Each report is a traceback. Its last line names the error, and the line that starts with File gives the line number.

Python
say_hi()

def say_hi():
    print("Hi!")
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    say_hi()
    ^^^^^^
NameError: name 'say_hi' is not defined
Python
def greet(name):
    print(f"Hello, {name}!")

greet()
Output
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    greet()
    ~~~~~^^
TypeError: greet() missing 1 required positional argument: 'name'
Python
def double(n):
    print(n * 2)

result = double(4) + 1
print(result)
Output
8
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    result = double(4) + 1
             ~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Exercise

Change square() so it returns the result instead of printing it, and the program prints 58. The starter prints 9 and 49 and then stops with a TypeError, because square() has no return statement and each call gives back None.

Python
def square(n):
    print(n * n)

total = square(3) + square(7)
print(total)
Output
Show the solution
def square(n):
    return n * n

total = square(3) + square(7)
print(total)

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    def f():
        return 1
        print("done")
    
    print(f())
  2. 2What does this program print?

    def show(n):
        n * 2
    
    print(show(5))
  3. 3A function starts with def add(a, b). What are a and b called?

  4. 4What happens when Python runs a def statement?

  5. 5What does this program print?

    def add(a, b):
        return a + b
    
    print(add("3", "4"))

Frequently asked questions

What is a function in Python?
A function is a named block of code that runs only when you call it. You define it with def, give it parameters for the values it needs, and send a result back with return.
How do I call a function in Python?
Write its name followed by parentheses, with any arguments inside, as in greet("Ada"). The parentheses are what run the function, and for a function you wrote, its def statement must have run before the call.
What does a Python function return if it has no return statement?
It returns None. A return with nothing after it also gives back None, and so does a function that ends without reaching any of its return statements.
What is the difference between return and print in Python?
return hands a value back to the code that called the function, which can store it or calculate with it. print() only shows a value on the screen, and a function that prints without returning gives back None.
What are built-in functions in Python?
Built-in functions are the functions Python provides without any import, such as print(), len(), input(), int() and sorted(). Functions you write yourself with def are called user-defined functions.
Can a Python function return more than one value?
Yes. Separate the values with commas, as in return total, count, and Python sends them back together as one tuple. The caller can unpack that tuple into separate variables in one assignment.
Do I have to define a function before calling it in Python?
Yes. The def statement must run before the line that calls the function, or Python raises NameError. Code inside a function body runs only when that function is called, so it may call a function defined lower in the file, as long as both defs have run by then.