A function in Python is a block of operations performed when the function is called. The function can take input parameters and use these to make calculations. Functions can also return values when the function is executed.
A significant advantage of functions in python is that you do not need to write the same code multiple times. You can call the function instead. A function is a block of operations that are performed when called. This means that instead of rewriting the same code several times, we can instead reuse code that is run multiple times, in different places in the program. A function can get one or more values, so-called input parameters, and can also send back, return one or no value. By return is meant what the method “returns” when it has performed the operations it contains. A method is always terminated when a value has been returned.
Methods are a very powerful tool because they are entirely independent of other code and can be called from other methods if desired. The uses of methods are many, and they help to structure and simplify the programs we create.
You can imagine a method like a black box. First, you send one or more values into the box and get another one, but you do not need to know what is actually happening in the box, how the code is programmed. The important thing is that you know what happens when the method is called. This abstracts the program and creates a more compact program.
In this chapter, we will first discuss in detail how a function works and why we use it. Additionally, we will go look at different types of functions and what you need to consider when returning values. Finally, the chapter ends with a few examples where you get the opportunity to create a couple of functions.