The Python programming language has two distinct types of functions:
- built-in capabilities
- individual functions
Up until this point, we have utilized numerous built-in functions in our code, such as print() and sum(). So, we are somewhat familiar with calling functions. Our Python program already has built-in functions; all we need to do is call them whenever we need them to work.
To define a function, we must use the def keyword and the function’s name enclosed in two parentheses. To send arguments or parameters to a function, use parenthesis. Parameters are simply values sent in the parenthesis, to put it simply. For instance, if two integers are added using a function, both numbers will be supplied as parameters in the parenthesis. A colon is used to enter the function’s body after the parentheses. Some functions have the option of returning a value to the caller; in these cases, a return statement is added at the end of the function body and returns the value that the function has calculated.
It’s really easy to call a function; all we have to do is include the closing parenthesis with the function’s name. If the function needs any arguments, we include them in the parentheses; but, if it doesn’t return anything, we leave the parenthesis empty.
After spending a lot of time talking about functions and how to use them, let’s move on to the benefits of doing so:
When working on a large project, we prefer to create as many functions as we can, allowing each member of our team to use them.
We can reduce the repetition of code to some extent by using functions. The more lines of code there are, the less efficient the program will be. Additionally, using the same code more than once will only make the code congested.
The use of functions ensures the reuse of code. A function can even be used inside of another function or anywhere else in our code.
We can save a lot of time by creating a function of code that we will use repeatedly.
Docstrings
Documentation string is abbreviated as docstring. Its goal is to provide the coder with a quick overview of the function’s functioning. It is optional and must be the first string in a function, however it is always a good idea to have it while working on program with several functions. A docstring is fairly easy to write because all it consists of is a string enclosed in three double quotes, three times (“”” “””) on either side of the string. However, it must appear in the function’s body’s first line of code. When calling a docstring, the function’s name is followed by. doc_.