Functions allow us to write several lines of code, that may need to be called at different times in our code, and to call all of the code, with using just the function name, and some parameters.
Sometimes functions are used to make code more readable, calling a function by a logical name, rather than seeing a bunch of code.
Sometimes a function is used as part of the DRY programming method. DRY stands for Don’t Repeat Yourself. In software engineering, don’t repeat yourself (DRY) is a principle of software development, aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. – Wikipedia
There are several advantages to using functions, including:
- Simpler Code – Often code is simpler to understand when it is logically grouped together in functions
- Code Reuse – no need to write things multiple times, and if you find an error, you only have to fix it in one place.
- Better Testing – You can test one section of code at a time reducing testing time, and making it faster to find and fix errors. This goes back to my suggestion of write a little code, test a little code. In this case, a function is a small defined section that is easy to test.
- Faster Development – especially when working on teams, and different functions can be assigned to different developers.
Function Types
There are two major types of functions in Python; Void Functions and Value Returning Functions.
A void function doesn’t return a value. It simply executes the code, and returns back to the point where it was called. Think of the print
function. When you call it, it performs and action – prints something to the screen, and then exits, returning you to the next line.
A value returning function is called, and returns a value back to the calling section of code. This allows a variable to be set, condition to be checked, etc. In this case, think of the input function. The input
function, displays something to the screen, and when the user enters the value, it returns it back to the program, so we can store that value in a variable.
All functions, must be called by a name. This name has the same rules as a variable does for being named. It must start with a letter, or underscore. The name is case sensitive, and it can contain numbers (just not start with them). Finally, the name cannot be a reserved word in Python.
The general form for a function is:
def function_name() :
statement 1
statement 2
etc...
Notice that it uses indentation to determine what is part of the body, just like loops and if statements.
Notice that is requires the def keyword, to let you know we’re defining the function, and after the name, are an open and closing set of parentheses, followed by a colon (:).
Functions in Python was originally found on Access 2 Learn