Skip to content
Happy Programming Guide
Start learning
Python

Python Functions Explained

Defining functions, parameters and defaults, keyword arguments, return values, scope, docstrings and when to split code into functions.

A Python function bundles steps under a name so you can run them whenever you want.

Python
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

print(celsius_to_fahrenheit(30))   # 86.0

The anatomy#

Python
def greet(name, greeting="Hello"):
    """Return a friendly greeting."""
    return f"{greeting}, {name}!"

print(greet("Ada"))                    # Hello, Ada!
print(greet("Ada", "Welcome"))         # Welcome, Ada!
print(greet(greeting="Hi", name="Sam"))  # Hi, Sam!
  • def starts the definition, and the line ends in a colon
  • The indented block is the body
  • The string on the first line is a docstring — visible via help(greet)
  • Naming arguments when calling makes long calls far more readable

Return: one value or several#

Python
def stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

low, high, average = stats([4, 8, 15, 16])
print(low, high, average)

Python returns a tuple, and you unpack it into separate names.

A function with no return gives back None:

Python
def show(x):
    print(x)

result = show(5)     # prints 5
print(result)        # None

Returning early#

return stops the function immediately. Handling awkward cases first keeps the main logic un-nested:

Python
def divide(a, b):
    if b == 0:
        return None
    return a / b

Scope#

Python
total = 0

def add(n):
    total = n          # creates a new local variable
    return total

add(5)
print(total)           # still 0

Functions can read outer variables but not reassign them without the global keyword. Avoid global — return the value and assign it at the call site instead. Code that only depends on its arguments is far easier to test.

Accepting any number of arguments#

Python
def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))       # 6

def describe(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

describe(name="Ada", age=36)

*args collects extra positional arguments into a tuple; **kwargs collects named ones into a dictionary.

Lambdas#

Python
double = lambda n: n * 2
print(double(4))     # 8

people = [{"name": "Ada", "age": 36}, {"name": "Sam", "age": 24}]
people.sort(key=lambda p: p["age"])

A lambda is a one-expression function with no name. It is genuinely useful as a key= argument and rarely worth it anywhere else.

Type hints and docstrings#

Python
def apply_discount(price: float, percent: float = 10) -> float:
    """Return the price after taking off a percentage."""
    return price - (price * percent / 100)

Python does not enforce the hints, but your editor uses them for autocomplete and warnings.

Questions people ask#

How long should a function be?

Short enough to fit on your screen and be described in one sentence. If the description needs an “and”, it is probably two functions.

Can functions call themselves?

Yes — that is recursion. It suits problems that break into smaller copies of themselves, like walking a folder tree. Loops are clearer for most everyday work.

What is the difference between an argument and a parameter?

A parameter is the name in the definition; an argument is the actual value you pass in. Most people use the words interchangeably.

Where to go next#

Try a projectBuild a Python calculator

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *