A function is a named block of code that does one job. You write it once, then call it by name whenever you need that job done. You've already used Python's built-in functions, such as print(), len() and input(). Now you'll write your own.
Functions keep programs short and organised. Instead of copying the same five lines into three places, you put them in a function and call it three times. If you need to fix something, you fix it in one place. Good function names also make code read like a set of clear steps.
In this lesson you'll define functions with def, pass in values with parameters, send results back with return, and give parameters default values.
Defining and calling a function
def say_hello():
print("Hello!")
print("Nice to see you.")
say_hello()
say_hello()defstarts a function definition, followed by the name, brackets and a colon.- The indented lines below are the function's body.
- Defining a function doesn't run it. Calling it,
say_hello(), does. You can call it as many times as you like. - A function must be defined above the line where you first call it.
Parameters and arguments
Parameters let a function work with different values each time:
def greet(name):
print(f"Hello, {name}!")
greet("Ada")
greet("Linus")name is a parameter: a placeholder in the definition. "Ada" and "Linus" are arguments: the real values you pass in when you call it. Separate several parameters with commas, def add(a, b):, and pass the arguments in the same order.
Returning a value
return sends a result back to wherever the function was called, so you can store it or use it in another calculation:
def area(width, height):
return width * height
room = area(4, 3)
print(room) # 12
print(area(2, 5) + 1) # 11return also ends the function straight away. A function without a return gives back the special value None. Printing and returning are different: print() shows a value to the person running the program, while return hands it back to your code.
Default and keyword arguments
Give a parameter a default value with =. If the caller leaves that argument out, the default is used:
def make_coffee(size="medium", sugar=0):
return f"A {size} coffee with {sugar} sugar"
print(make_coffee())
print(make_coffee("large"))
print(make_coffee(sugar=2))The last call uses a keyword argument, sugar=2, which names the parameter directly so you can skip size and leave it at its default. Parameters with defaults must come after the ones without.
Returning early and returning several values
A function can contain more than one return. The first one reached ends the function, which lets you deal with special cases at the top and keep the main logic unindented:
def shipping_cost(total):
if total >= 50:
return 0 # free delivery, stop here
if total == 0:
return 0
return 4.99These early returns are often called guard clauses. They are easier to read than a deep stack of nested if and else blocks.
To hand back more than one result, separate the values with commas. Python packs them into a tuple, and the caller can unpack them into separate variables:
def split_bill(total, people):
each = round(total / people, 2)
return each, people
share, count = split_bill(60, 4)The next lesson, function arguments and scope, covers this and other flexible patterns in more depth.
Documenting a function with a docstring
A string written as the first line of a function body is its docstring. It explains what the function does, and tools such as help() and code editors display it:
def bmi(weight_kg, height_m):
"""Return body mass index, rounded to one decimal place."""
return round(weight_kg / height_m ** 2, 1)
help(bmi)You can also add type hints to say what kinds of values a function expects and returns: def bmi(weight_kg: float, height_m: float) -> float:. Python doesn't enforce them at run time, but editors use them to catch mistakes before you run the code.
Python Functions Syntax
Function syntax
def function_name(param1, param2="default"):
# body
return result
value = function_name(arg1)
value = function_name(arg1, param2=arg2)Python Functions Summary
def name(parameters):defines a function; its body is indented.- Call a function with its name and brackets:
name(arguments). - Parameters are placeholders; arguments are the values passed in.
returnsends a value back and ends the function. Without it, the result isNone.- Default values make parameters optional; keyword arguments name them directly.
Python Functions Examples
Each example shows the code, the output it produces and what each part does.
A reusable greeting
def welcome(name, course):
print(f"Welcome, {name}!")
print(f"You've joined the {course} course.")
print()
welcome("Priya", "Python")
welcome("Tom", "SQL")Welcome, Priya!
You've joined the Python course.
Welcome, Tom!
You've joined the SQL course.
Line-by-line explanation
- Line 1Two parameters, name and course.
- Lines 6 to 7The same three lines run twice, with different values each time.
Functions that return answers
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
def is_freezing(c):
return c <= 0
today = 18
print(f"{today}°C is {celsius_to_fahrenheit(today)}°F")
print("Freezing?", is_freezing(today))
print("Boiling point:", celsius_to_fahrenheit(100))18°C is 64.4°F
Freezing? False
Boiling point: 212.0Line-by-line explanation
- Line 2return hands the converted value back to the caller.
- Line 5Functions that answer a yes/no question often start with "is" and return True or False.
- Line 9A returned value can be used directly inside print().
Functions working together
def average(numbers):
return sum(numbers) / len(numbers)
def grade(score):
if score >= 80:
return "Merit"
return "Pass"
results = [72, 88, 91]
avg = average(results)
print(f"Average {avg:.1f}: {grade(avg)}")Average 83.7: MeritLine-by-line explanation
- Lines 1 to 2A function can take a whole list as its argument.
- Lines 5 to 7Return early. Once the first return runs, the function ends.
- Line 11One function's result is passed straight into another.
Common Python Functions Mistakes
Forgetting the brackets when calling
def roll_dice():
return 4
print(roll_dice) # <function roll_dice at 0x...>print(roll_dice()) # 4Without brackets you refer to the function itself instead of running it.
Printing instead of returning
def double(n):
print(n * 2)
result = double(5) + 1 # TypeError: None + 1def double(n):
return n * 2
result = double(5) + 1 # 11Calling before defining
show_menu()
def show_menu():
print("1. Start 2. Quit")def show_menu():
print("1. Start 2. Quit")
show_menu()Python reads from top to bottom, so the first version stops with a NameError.
Python Functions in Real Projects
Functions in real programs
Real programs are built from many small functions: load_orders(), calculate_tax(amount), send_receipt(email). Python's huge collection of libraries is really just a set of ready-made functions you can import and call, which is one of the reasons Python is so productive.
Python Functions FAQ
What is the difference between a function and a method in Python?
A function is called on its own, like len(items). A method is a function that belongs to an object and is called with a dot, like items.append(4) or name.upper(). You'll write your own methods when you reach the classes lesson; they are defined with def inside a class.
What does a Python function return if there is no return statement?
It returns None. That's why result = print("hi") leaves result set to None. If you see None printed unexpectedly, check whether the function you called prints its answer instead of returning it.
Can I define a function inside another function?
Yes. An inner function is visible only inside the outer one, which is useful for small helpers that nothing else needs. Inner functions can also read the outer function's variables, an idea used by closures and decorators later in the course.
Should I use def or lambda?
Use def for anything you want to name, reuse, document or test. A lambda is a one-expression function without a name, best kept for short rules passed directly to another function, such as sorted(people, key=lambda p: p["age"]).
How many parameters should a function have?
There is no hard limit, but functions with more than three or four parameters become hard to call correctly. If you find yourself passing many related values, consider grouping them in a dictionary, a dataclass or an object, or splitting the function into smaller ones.
Python Functions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the function so it returns double the number it's given.
double(n):
n * 2
What does this print?
def add(a, b=10):
return a + b
print(add(5), add(5, 1))
What does this print?
def shout(word):
print(word.upper())
result = shout("hey")
print(result)
Which definition is valid?
What does this function return when called as check(-2)?
def check(n):
if n > 0:
return "positive"
Python Functions Quiz
5 questions to check what you learned.
Which keyword defines a function in Python?
- function
- def
- func
- define
What does a function return if it has no return statement?
- 0
- An empty string
- None
- An error
In
def area(w, h):andarea(3, 4), what are 3 and 4?- Parameters
- Return values
- Defaults
- Arguments
What does this print?
def f(x): return x * 2thenprint(f(f(3)))- 12
- 6
- 9
- 36
Which call uses a keyword argument?
- greet("Ada")
- greet(name="Ada")
- greet["Ada"]
- greet.name("Ada")