Functions in Python

Published by Brayan K

A function in Python is a named, reusable block of code that performs a specific task, optionally takes inputs (arguments) and returns a result, so you can run the same logic many times without repeating it.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

def stores a block of code; a call runs it

A function starts with def, a name, parentheses and a colon, followed by an indented body. Defining it only stores the body under that name. Nothing in it runs until you call the function, by writing its name with parentheses:

def greet():
    print("Hello!")
    print("Welcome back.")

print("Before the calls")
greet()
greet()

# ✅ Expected output:
# Before the calls
# Hello!
# Welcome back.
# Hello!
# Welcome back.

Python reads the def first and keeps the body without running it, which is why "Before the calls" comes first. Each greet() then runs the whole body. Because Python works from the top down, a function has to be defined before the line that calls it:

greet()

def greet():
    print("Hello!")

# ✅ Expected error:
# NameError: name 'greet' is not defined

Leave out the parentheses and nothing is called at all:

def greet():
    print("Hello!")

greet
print(type(greet))

# ✅ Expected output:
# <class 'function'>

greet on its own is the function itself, a value like a number or a piece of text, so that line does nothing and raises no error. The parentheses are what run it.

Parameters and arguments

The names in a def's parentheses are parameters. The values you pass in a call are arguments, and each call gives the parameters that call's values, in order:

def greet(name, greeting):
    print(greeting, name)

greet("Ada", "Hello")
greet("Linus", "Hi")

# ✅ Expected output:
# Hello Ada
# Hi Linus

Every parameter needs an argument, so a call with too few stops the program:

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

print(add(5))

# ✅ Expected error:
# TypeError: add() missing 1 required positional argument: 'b'

The message names the function and the parameter that got nothing. Too many arguments fail the same way: add(1, 2, 3) stops with TypeError: add() takes 2 positional arguments but 3 were given.

return hands a value back

return sends a value back to the line that made the call, where you can store it, print it or use it in a calculation:

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

total = add(5, 3)
print(total)
print(add(10, 20) + add(1, 2))

# ✅ Expected output:
# 8
# 33

Printing inside a function is not the same as returning. A function without a return still hands something back, the special value None:

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

result = double(5)
print(result)

# ✅ Expected output:
# 10
# None

The 10 is printed inside double; what comes back is None. Try to calculate with it and the program stops, right after the 10:

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

result = double(5)
print(result * 3)

# ✅ Expected output:
# 10

# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

When you see 'NoneType' in an error, check whether the function you called forgot its return.

return ends the function at once

Python leaves a function at the first return that runs, so nothing after it in that call runs. That makes it the cleanest way to deal with a problem case first and stop, the guard clause from Control Flow:

def average(total, count):
    if count == 0:
        return 0
    return total / count

print(average(10, 4))
print(average(0, 0))

# ✅ Expected output:
# 2.5
# 0

Without the first return, average(0, 0) would divide by zero. A return also leaves every loop it sits in, which is the simple way out of loops inside loops:

def find_pair(target):
    for a in range(1, 10):
        for b in range(1, 10):
            if a * b == target:
                return a, b

print(find_pair(12))
print(find_pair(97))

# ✅ Expected output:
# (2, 6)
# None

For 12, the first matching pair ends the search. No pair below 10 multiplies to 97, so both loops run to the end, no return runs, and the function hands back None.

Default values and keyword arguments

A parameter can have a default value, used when the call leaves that argument out. And a call can name the parameter it's giving a value to, a keyword argument, which lets you skip a default or give arguments in any order:

def order_total(price, quantity=1, discount=0):
    return price * quantity - discount

print(order_total(4))
print(order_total(4, 3))
print(order_total(4, discount=1))
print(order_total(quantity=2, price=5))

# ✅ Expected output:
# 4
# 12
# 3
# 10

Parameters with defaults have to come after the ones without; writing def f(a=1, b): is a SyntaxError, though its wording differs between Python versions. In a call, it's the other way round: positional arguments go first, and one after a keyword argument stops the program before it starts:

def order_total(price, quantity=1, discount=0):
    return price * quantity - discount

print(order_total(price=4, 3))

# ✅ Expected error:
# SyntaxError: positional argument follows keyword argument

Two more mistakes give errors that name the problem: a name the function doesn't have, as in order_total(4, tip=1), gives TypeError: order_total() got an unexpected keyword argument 'tip', and a value for the same parameter twice, as in order_total(4, price=5), gives TypeError: order_total() got multiple values for argument 'price'. One default needs care: a list as a default value is shared by every call, a trap None & NoneType shows how to avoid.

Returning two values

return a, b hands back both values together, as a tuple, and the caller can unpack them into two names, the way Variables and Data Types unpacks x, y = 1, 2:

def min_max(a, b):
    if a < b:
        return a, b
    return b, a

low, high = min_max(7, 3)
print(low, high)
print(min_max(1, 9))

# ✅ Expected output:
# 3 7
# (1, 9)

Printed whole, the pair shows in parentheses: that's a tuple, which Tuples covers. Forget the return and the unpacking is where it shows up:

def min_max(a, b):
    if a < b:
        low, high = a, b
    else:
        low, high = b, a

low, high = min_max(7, 3)

# ✅ Expected error:
# TypeError: cannot unpack non-iterable NoneType object

The function works out both values and then drops them, so the call gives None, and None can't be split into two.

Names made inside a function stay inside

A variable created in a function's body is local: it exists only while that call runs. Outside, use what the function returns:

def rectangle(w, h):
    area = w * h
    return area

print(rectangle(3, 4))
print(area)

# ✅ Expected output:
# 12

# ✅ Expected error:
# NameError: name 'area' is not defined

A function can read a variable defined outside it, but assigning to that name inside the function makes a new local variable instead of changing the outside one, and reading it before that assignment stops the program with an UnboundLocalError (whose wording differs between Python versions). Passing values in and returning results keeps a function clear of all that; Scope: global, nonlocal & LEGB has the full rules.

A string on the first line of the body is the function's docstring. It says what the function does, and help() and code editors show it, as in the leap-year solution below.

Where functions go from here

Functions that accept any number of arguments use *args & **kwargs. A function small enough to write in one line can be a lambda, from Lambda Functions. And a function that meets a problem it can't handle, such as a division by zero, can raise an error for the caller to deal with, which Exception Handling covers.

Practice: a temperature converter

Fill the three blanks with the values in the hint lines, in order, so that the function returns its answer and the second call converts boiling water.

___ to_fahrenheit(celsius):
    ___ celsius * 9 / 5 + 32

print(to_fahrenheit(0))
print(to_fahrenheit(___))

# 👉 replace ___ with def
# 👉 replace ___ with return
# 👉 replace ___ with 100

# ✅ Expected output:
# 32.0
# 212.0

On your own: is_leap(year)

A year is a leap year when it divides exactly by 4, except that a year dividing by 100 is a leap year only if it also divides by 400. Write a function is_leap(year) that returns True or False, give it a docstring, and print its answer for 2024, 1900 and 2000: only 1900 should be False. Then compare with this solution:

def is_leap(year):
    """Return True if year is a leap year in the Gregorian calendar."""
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

print(2024, is_leap(2024))
print(1900, is_leap(1900))
print(2000, is_leap(2000))

# ✅ Expected output:
# 2024 True
# 1900 False
# 2000 True

The function returns the comparison itself: it already is True or False, so there's no need for an if.

Practice quiz

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

  • 0
  • An empty string
  • None
  • An error

Answer: None. Every call hands something back. Without a return, that's None.

def double(n): print(n * 2), then x = double(4). What is x?

  • 8
  • None
  • 4
  • An error

Answer: None. double prints 8 but returns nothing, so x is None.

def add(a, b): return a + b. What happens when you call add(5)?

  • It returns 5
  • It returns None
  • It stops with a TypeError: missing 1 required positional argument
  • It waits for the second value

Answer: It stops with a TypeError: missing 1 required positional argument. Every parameter without a default needs an argument.

def total(price, quantity=1): return price * quantity. What is total(4, quantity=3)?

  • 12
  • 7
  • 4
  • An error

Answer: 12. The keyword argument replaces the default, so it's 4 * 3.

Which of these calls is a SyntaxError?

  • add(1, 2)
  • add(a=1, b=2)
  • add(1, b=2)
  • add(a=1, 2)

Answer: add(a=1, 2). A positional argument can't follow a keyword argument.

What happens to the lines after a return that runs?

  • They run after the value is returned
  • They never run in that call
  • They run on the next call
  • They're a SyntaxError

Answer: They never run in that call. return leaves the function at once.

def rectangle(w, h): area = w * h; return area. Outside the function, after rectangle(3, 4), what does print(area) do?

  • Prints 12
  • Prints None
  • Stops with a NameError
  • Prints 0

Answer: Stops with a NameError. area exists only inside the function while it runs.

min_max(a, b) returns b, a when a is the larger one. After low, high = min_max(7, 3), what is low?

  • 7
  • 3
  • (3, 7)
  • None

Answer: 3. The function returns the pair 3, 7, and unpacking gives low the first value.

Continue this course

Frequently asked questions

What's the difference between a function and a method?

A method is a function that belongs to a value and is called through it with a dot, like "hi".upper() or a list's append(). You write methods of your own inside a class, which Object-Oriented Programming covers.

Can a function call itself?

Yes. That's recursion: the function calls itself on a smaller version of the problem until it reaches a case it can answer directly. Advanced Functions & Parameters Masterclass covers it.

Related lessons