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.
Before this lesson: Python Variables, Python if, elif and else, Python for Loops
2Python Functions: diagram
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.
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.
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
- Python Cheat Sheet (Python 3.13 Quick Reference) — This Python cheat sheet puts the most-used syntax for Python 3.13 into tables of tested one-liners: numbers, …
- Python Functions Cheat Sheet: def, args, lambda, scope — Define a Python function with `def name(parameters):` and `return` a result; use default values, `*args` and …
- Python Function vs Method: What Is the Difference? — A **function** is a standalone block of code you call by name, like `len(items)`, while a **method** is a fun…
- Python print() vs return: What Is the Difference? — `print()` **displays** a value on the screen and gives you nothing to work with, while `return` **sends a val…
- Python Program for Linear Search (with Examples) — Linear search checks every item of a list from left to right and returns the index of the first match, or `-1…
- Python Program to Check Prime Number — A prime number is a whole number greater than 1 that has no divisors other than 1 and itself; in Python you t…
- Python Simple Calculator Program — A simple Python calculator reads two numbers and an operator with `input()`, then uses `if/elif` (or a dictio…
- Python Tower of Hanoi Program (Recursion Explained) — The Tower of Hanoi puzzle is solved in Python with a short recursive function: move n − 1 disks to the spare …
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.
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.
- Line 1
defcreates a function with three parameters.discountandshippinghave default values, so callers may leave them out. Nothing runs yet. - Line 2The docstring describes what the function returns.
- Line 3-5The body adds up the prices, takes off the discount and returns the rounded total.
returnsends that number back to the caller. - Line 7An ordinary list is created, ready to be passed in as an argument.
- Line 9Only
pricesis given, so the defaults apply: no discount, 4.99 shipping, giving 37.49 + 4.99 = 42.48. - Line 10The second positional argument fills
discount: 10% off 37.49 is 33.74, plus shipping makes 38.73. - Line 11A keyword argument sets
shippingdirectly, skipping overdiscount, which keeps its default of 0: the total is 37.49. - 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.
- 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✓ 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✓ 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"))✓ 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 ✓ CompletedComplete the function square(n) so that it returns n multiplied by itself. For example, square(4) returns 16.
def square(n):
# return n multiplied by itself
pass
print(square(4))def square(n):
return n * n
print(square(4))
2. Predict the calls
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
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)adding 1 10
adding 1 2
11 3
adding 5 1
12
2 more exercises → 4 more examples
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