Today, we will discuss what functions are and why we need them.
A function can be thought of as a robot that can do a certain task whenever required. A function is useful if several lines of code are redundant, that is, they are being used over and over in different parts of a program. Instead of calling those lines of code, we can just call the function. Of course, we have to initially make the code in the function.
To make a function, we use the following syntax:
def function_name(parameter1, parameter2, ... parameterN): (Minimum no parameters)
function_body
Nothing has run because we only made the function, we did not use it. To call the function, we use the following syntax:
function_name(<Optional>parameter1, parameter2, ... parameterN)
In this example, it is not obvious as to why we use functions, especially because it is doing a one-line task and is not taking any input, nor is it returning any output. It simply prints a value. These are called chatterbox functions. What we really want are fruitful functions, that is, functions that quietly take their input through the parameters and then give an output using the return keyword. Here is the syntax of a fruitful function:
def function_name(parameter1, parameter2, ... parameterN): (Minimum one parameter)
<do something>
return <result>
For example, let us say we wish to return whether a number is even or not. We will return True if it is even, and False if it is not even. Because of what it will output, we can set the function name as is_even, and the parameter as number. And to check if the number is divisible by two or not (That is, if it is even or not) we can use modulus, which gives the remainder of a division (If the division is neat and clean, that is, has no decimals, the modulus operator gives us zero):
The program returns the result of whether number modulo divided by two is equal to zero. If so, it returns True, otherwise, it returns False.
Those are the uses of Functions.