Introduction to Functions
Learn how to use functions and recursion to improve the readability and efficiency of the code.
A function is a segment of code that is isolated from the main code segment. A function is called from a section of code. When the function’s code has been executed, it returns to the calling code.
Why functions?
A function is a reusable piece of code. Think of a function a s a box is designed to perofrm a specific task. This box recieves certain inputs (arguments or parameters) and based on this input, produces a corresponding result (output). Once a function is defined, it can be called (or invoked) from other parts of the program as many times as needed.
Benefits of a function
A function offers several benefits. Some of these are written below:
Reusability: A function allows us to write code only once and reuse it as many times as we want, thus reducing the lines of code.
Modularity: A function allows us to divide complex code into smaller, more manageable problems. If we have a big complex problem, we can divide this problem into several parts and thus create a function to tackle each of these problems.
Maintainability and Readability: A code written in a function is more meaningful and simple than the whole code written in the main function. As the code is divided into pieces, it is also easier to understand, manage and update. If we want to change functionality, we only need to chnage the code in that certain function and everything else woruld remain the same.
Syntax
The general form of a function is:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy