How to call a user-defined function in Python 3?
A function is a set of organized instructions defined under a block.
Python being a powerful language has a lot of in-built functions, for instance, we can mention print(), len() and many more which are provided in the given link.
Also, user, while writing the code can define functions which keeps this in the category of User-defined functions in Python.
The syntax for defining a function in Python 3
Below is given the syntax of creating a function:
def function_name(arguments): ''' Function doc-string is defined ''' #Function operation ... ... return expression
Above is the way to define any function in Python. Generally, in-built functions in Python 3 have doc-strings. It’s written below the function which becomes useful
to analyze the behavior of the function i.e the arguments, return type, etc. So, we should get a habit of writing the docstring but again, it is not necessary.
Example of creating a user-defined function
Now, I hope we have got a good knowledge of functions in Python3. let’s have a look at its implementation given below:
def add(a,b): return a+b result_1 = add(5,4) print(result_1) result_2 = add(add(0,4),5) print(result_2)
In the above code, it defines an add function which passes 2 parameters in it. Unlike other languages we do not need to define the return type of the function, also the type of parameter passed. Here the code has 2 lines to print in which the parameters are
- 2 Integers
- An Integer and a function itself
- How to create a Python function with optional arguments
- Python Zip, enumerate function and frozenset() method
Initially, the output is 9. We obtain it just as the function is called and the answer gets stored in the variable result_1. And also next result which is result_2. It is where python comes to play. Here we have a function as a parameter inside the parameter section of the function which is an interesting way to call the function.