def

In Python, the def keyword defines a function, which is a reusable block of code that may accept data input, perform a specific computation or task, and return a result or produce a side effect. Functions allow you to encapsulate a piece of logic and execute it whenever you need to by calling the function’s name with a pair of parentheses.

Python def Keyword Examples

Here’s a short example of how to define a function using the def keyword:

Python
>>> def greet(name):
...     return f"Hello, {name}!"
...

>>> greet("Alice")
'Hello, Alice!'

In this example, the def keyword creates a function named greet() that takes a single argument, name. When you call greet("Alice"), it returns the string "Hello, Alice!".

Python def Keyword Use Cases

  • Encapsulating code into reusable functions to avoid repetition and improve maintainability
  • Implementing complex logic in a modular way by breaking it down into smaller, manageable functions
  • Enhancing code readability by providing descriptive function names and documentation
  • Facilitating testing and debugging by isolating specific pieces of logic

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. 6, 2025 • Reviewed by Dan Bader