function

A function is a self-contained block of code that performs a specific task. Think of it as a small program within your program that you can run (or “call”) whenever you need it.

Here’s how you create a function in Python:

Python Syntax
def function_name(parameter1, parameter2):
    # Function body: code that runs when the function is called
    result = parameter1 + parameter2
    return result  # Send back the result to whoever called the function

The key components of a function definition in Python are:

  • def: The keyword that tells Python you’re defining a function
  • function_name: A name you choose that describes what the function does
  • parameters: Variables listed in parentheses that receive input values
  • Function body: The indented block of code that runs when the function is called
  • return: The keyword used to send a result back (optional)

Functions are fundamental building blocks in Python programming that help you:

  • Break down complex problems into manageable pieces
  • Avoid repeating code
  • Make your code more organized and easier to maintain
  • Create reusable solutions that can be shared across projects

Python comes with many built-in functions, but you can also define your own custom functions to suit your specific needs. Once defined, you can call a function by its name followed by parentheses, possibly passing arguments inside these parentheses if the function requires them.

Example

Here’s a quick example of a Python function that takes two numbers and returns their sum:

Python
>>> def add(a, b):
...     return a + b
... 

>>> add(3, 5)
8

In this example, add() is a function that has two parameters, a and b, and returns their sum. You call the function with the arguments 3 and 5, and it returns 8, which is then printed to the console.

Tutorial

Defining Your Own Python Function

In this tutorial, you'll learn how to define and call your own Python function. You'll also learn about passing data to your function, and returning data from your function back to its calling environment.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 14, 2025 • Reviewed by Dan Bader