In Python, the function is a block of code defined with a name. We use functions whenever we need to perform the same task multiple times without writing the same code again. It can take arguments and returns the value.
Python has a DRY principle like other programming languages. DRY stands for Don’t Repeat Yourself. Consider a scenario where we need to do some action/task many times. We can define that action only once using a function and call that function whenever required to do the same activity.
Function improves efficiency and reduces errors because of the reusability of a code. Once we create a function, we can call it anywhere and anytime. The benefit of using a function is reusability and modularity.
Table of contents
Types of Functions
Python support two types of functions
- Built-in function
- User-defined function
Built-in function
The functions which are come along with Python itself are called a built-in function or predefined function. Some of them are listed below.range(), id(), type(), input(), eval() etc.
Example: Python range() function generates the immutable sequence of numbers starting from the given start integer to the stop integer.
User-defined function
Functions which are created by programmer explicitly according to the requirement are called a user-defined function.
Creating a Function
Use the following steps to to define a function in Python.
- Use the
defkeyword with the function name to define a function. - Next, pass the number of parameters as per your requirement. (Optional).
- Next, define the function body with a block of code. This block of code is nothing but the action you wanted to perform.
In Python, no need to specify curly braces for the function body. The only indentation is essential to separate code blocks. Otherwise, you will get an error.
Syntax of creating a function
def function_name(parameter1, parameter2):
# function body
# write some action
return valueCode language: Python (python)
Here,
function_name: Function name is the name of the function. We can give any name to function.parameter: Parameter is the value passed to the function. We can pass any number of parameters. Function body uses the parameter’s value to perform an actionfunction_body: The function body is a block of code that performs some task. This block of code is nothing but the action you wanted to accomplish.- return value: Return value is the output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).