Python Functions
Core Python Functions and Modules

Python Functions

1Python Functions: overview

A function is a named, reusable block of code that takes inputs (arguments), does some work, and can hand a result back with return.

GoalBy the end you can define and call your own functions, tell parameters from arguments, return values instead of printing them, and use default values, keyword arguments and docstrings.

Before this lesson: Python Variables, Python if, elif and else, Python for Loops

2Python Functions: diagram

Python Functionsroom = area(3, 4)call with argumentsarguments go inwidth = 3, height = 4parameters receive themresult = width * heightthe body runsreturn resultsend the value backvalue comes outroom = 12the caller gets 12
Calling a function sends the arguments in. They are stored in the parameter names, the body runs, and return hands one value back to the exact place where the function was called.

3Python Functions: explained step by step

A function packages a piece of work under a name. Once it's defined, you can run it as often as you like by calling it, with different inputs each time, instead of copying the same lines around your program. You have already used plenty of built-in functions such as print(), len() and max(). Now you'll write your own.

Python
def greet(name):
    """Return a friendly greeting for name."""
    return "Hello, " + name + "!"

message = greet("Asha")
print(message)
print(greet("Ben"))

Defining vs calling

def creates the function: the keyword, a name, parameters in brackets, a colon, and an indented body. Defining a function does not run its body; Python just remembers it under that name. The body runs only when you call the function by writing its name followed by brackets, like greet("Asha").

Parameters and arguments

The names listed in the def line (name above) are parameters: placeholders waiting for values. The actual values you pass in a call ("Asha") are arguments. At each call Python assigns the arguments to the parameters, so inside the body name holds "Asha" the first time and "Ben" the second.

return vs print

return sends a value back to the caller and ends the function straight away. The caller can store that value, print it, compare it or pass it to another function. print() only shows text on the screen; the caller gets nothing it can work with. A function that finishes without return gives back None.

Python
def with_shipping(price):
    return price + 5

def show_with_shipping(price):
    print(price + 5)

total = with_shipping(20) + with_shipping(30)
print("Total:", total)
result = show_with_shipping(20)
print("Result:", result)

Default and keyword arguments

A parameter can have a default value, as in def power(base, exponent=2). If the caller leaves that argument out, the default is used. Callers can also pass keyword arguments by name, as in power(base=2, exponent=3), which makes calls easier to read and lets you skip over optional parameters. Parameters with defaults must come after the ones without.

Docstrings

A string written as the first line of the body is a docstring. It explains what the function does, what it expects and what it returns. Editors show it as a tooltip, and help(greet) prints it. A good habit is one short sentence that starts with a verb, such as "Return ...".

Quick reference: Python Functions

4Python Functions: syntax

def function_name(param1, param2=default):
    """Explain what the function does."""
    # body
    return result

value = function_name(arg1)               # positional argument
value = function_name(arg1, param2=x)     # keyword argument

5Python Functions: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
def order_total(prices, discount=0, shipping=4.99):
    """Return the total after a percentage discount, plus shipping."""
    subtotal = sum(prices)
    subtotal = subtotal - subtotal * discount / 100
    return round(subtotal + shipping, 2)

cart = [19.99, 5.50, 12.00]

print(order_total(cart))
print(order_total(cart, 10))
print(order_total(cart, shipping=0))

big_order = order_total([120.00, 80.00], discount=15, shipping=0)
if big_order > 100:
    print("Free gift added! Total:", big_order)

print(order_total.__doc__)
Expected output42.48
38.73
37.49
Free gift added! Total: 170.0
Return the total after a percentage discount, plus shipping.

7Python Functions: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1def creates a function with three parameters. discount and shipping have default values, so callers may leave them out. Nothing runs yet.
  2. Line 2The docstring describes what the function returns.
  3. Line 3-5The body adds up the prices, takes off the discount and returns the rounded total. return sends that number back to the caller.
  4. Line 7An ordinary list is created, ready to be passed in as an argument.
  5. Line 9Only prices is given, so the defaults apply: no discount, 4.99 shipping, giving 37.49 + 4.99 = 42.48.
  6. Line 10The second positional argument fills discount: 10% off 37.49 is 33.74, plus shipping makes 38.73.
  7. Line 11A keyword argument sets shipping directly, skipping over discount, which keeps its default of 0: the total is 37.49.
  8. Line 13-15Because the function returns its result instead of printing it, the caller can store the value and make decisions with it: 200 minus 15% is 170.0.
  9. Line 17A function's docstring is stored in its __doc__ attribute.

8Python Functions: common mistakes

Calling a function before it is defined

✗ Wrong

print(square(4))

def square(n):
    return n * n
NameError: name 'square' is not defined

✓ Right

def square(n):
    return n * n

print(square(4))

Python runs a file from top to bottom, so the def must run before the first call. Put your function definitions near the top.

Printing instead of returning

✗ Wrong

def double(n):
    print(n * 2)

result = double(5) + 1
Prints 10, then TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

✓ Right

def double(n):
    return n * 2

result = double(5) + 1
print(result)

print() only displays the value; the function itself returns None. Use return so the caller gets the number, and print it outside if you want to see it.

Leaving out a required argument

✗ Wrong

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

print(greet("Asha"))
TypeError: greet() missing 1 required positional argument: 'greeting'

✓ Right

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

print(greet("Asha"))
print(greet("Ben", "Welcome"))

Every parameter without a default needs an argument. Pass both values, or give the parameter a sensible default.

9Python Functions: exercises

Write your answer, then press Check. The checks run in your browser.

1. Write a square function

Write code Easy

Complete the function square(n) so that it returns n multiplied by itself. For example, square(4) returns 16.

Your code
def square(n):
    # return n multiplied by itself
    pass


print(square(4))

2. Predict the calls

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
def add(a, b=10):
    print("adding", a, b)
    return a + b

x = add(1)
y = add(1, 2)
print(x, y)
print(add(b=1, a=5) * 2)

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

What is the difference between a parameter and an argument?

A parameter is the name in the def line, like price in def add_tax(price). An argument is the actual value passed in a call, like 50 in add_tax(50). When the function runs, each parameter is set to its argument.

Should my function print the result or return it?

Return it in almost every case. A returned value can be stored, tested, printed or passed to another function, while printed text is gone once it's on the screen. Print only when displaying something is the function's whole job.

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

It returns None. That's why result = print_something() leaves result set to None, and why using that result in a calculation raises a TypeError.

Further reading

10Next lesson

Up nextPython Function ArgumentsA function argument is the value you pass in a call, and Python matches each argument to a parameter either by position…

Related:
Python Function ArgumentsPython Lambda FunctionsPython Variable ScopePython Modules and Imports

← Python collections Module · All Functions and Modules lessons · Practise in the IDE