A function is a sequence of instructions or a block of statements that performs a specific task
These instructions or statements can also include call to other functions (or the same function)
Typically, function is used to group repetitive code or statements so that they can be called as a unit with a single statement
A function of a program can be thought of, as analogous to a function of a human body
For example when a person picks something with their hands then that person is performing the function of picking_something()
Similarly, a program can have a function of picking a file from a folder
Following is a simple function in Python, which takes a number, divides it by 2 and returns the value
def half(x):
return x/2
The above example only defines the function with a parameter x
(which is a variable)
This function has to be called or executed, similar to a person being told to pick something, which can be a book or a phone
Following code calls the above defined function with different values
half(20)
half(12.512)
half(44+10)
Above calls to the function returns values based on each input to the function
Now, if these values are to be displayed to the user when the program is run, then another function has to be used
In Python, this can be done with print()
function, which is a built-in function of Python
def half(x):
return x/2
print(half(20))
print(half(12.512))
print(half(44*10))
Assuming the above code is saved to a file named as function_test.py
then the program can be run to display the returned values like
Predefined functions are shipped with a programming language, and are of a wide-range in major programming languages
Eg: print() function of Python
Functions can also be defined by a programmer
Eg: half() function defined above
Parameters are variables, used in a function which are provided as input to function when called
The behaviour of a function can depend on the parameters accepted by it
A function might be defined to accept zero, one or more parameters
Both print() function and half() functions mentioned above take parameters