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.
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.
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.
The syntax of defining a function using the def keyword is shown below:
Syntax Explanation:
In the following example, we are defining two functions to display a welcome message and print a special message.
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.
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.
In the following example, we are creating a class to store employee details and using methods to display the information.
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.
We request you to subscribe our newsletter for upcoming updates.