Python def Keyword

Last Updated : 16 Apr 2026

The def keyword in Python is used to create functions that perform specific tasks.

In this chapter, you will learn about the def keyword, how functions are defined using it, and how it works in Python.

What is the def Keyword?

The def keyword is used to define a function. It helps us create reusable blocks of code that perform a specific task.

Using def keyword, we can write our own functions instead of repeating the same code again and again.

Defining Function Using def Keyword

We can define a function using the def keyword followed by the function name and parentheses. The code inside the function is written with proper indentation. A function can take inputs (parameters) and can also return a value using the return statement.

Syntax

The syntax of defining a function using the def keyword is shown below:

Syntax Explanation:

  • def: This is the keyword that is used to define a function.
  • function_name: This is the name of the function.
  • parameters: Inputs passed to the function (optional).
  • docstring: This parameter is optional description of the function.
  • function body: The main code of the function that performs the task.
  • return: The return statement that is used to return a result (optional).

Example of Defining Function Using def Keyword

In the following example, we are defining two functions to display a welcome message and print a special message.

Compile and Run

Output:

Welcome to Python Programming!  
Keep learning and keep growing!  

Explanation:

In this example, we created two functions: welcome() and special_message(). Both functions do not take any parameters. When we call them, each function runs its code and prints its respective message.

Use of the def Keyword in Classes

In Python, the def keyword is not only used to create functions but also to define methods inside a class. A method is a function that belongs to a class and works with its objects. These methods can access and modify the data (attributes) of the class.

Example

In the following example, we are creating a class to store employee details and using methods to display the information.

Compile and Run

Output:

Name: Rahul  
Role: Software Developer  
Salary: 60000  

Explanation:

In this example, we created a class Employee and used the def keyword to define methods inside it. The __init__() method initializes the object’s data, and show_details() displays the employee information.


Next TopicPython Modules