Creating a function in Python allows you to reuse code throughout your project. You can create a library of useful functions that can make your coding simplified.
To create a function use the def statement follow by the name of the function and then an open parenthesis and then follow by a list of parameters and then a closing parenthesis and a colon. Then the next line you press TAB to indent your function’s code.
Your function can return a value by specifying the return statement follow by some value.
Create a new file called Functions.py with the following code, or enter the code in your interpreter:
def add(a, b): return a + b result = add(2,5) print result
In the code above I have defined my function called Add with two parameters a and b which will take in an integer value. Then in the function body I am adding a and b together and return the result.
The next line I call the function Add and give it a value of 2 and 5 to be added and then assign the returned value to a variable called result, then I use the print statement to display the result. The expected value return should be displayed is 7.
Download the source code for this blog from my GitHub repository: