When programming, functions are of fundamental importance. Imagine you want to search at some places in your program in an array for a certain value. Your developed search algorithm is 10 lines long. If you insert these 10 lines every time you want to search for a value, there are 2 problems:
- The code becomes extremely confusing and difficult to understand.
- You may not always be looking for the same value and therefore need to change your search algorithm slightly. This has an enormous error potential and such errors, however small and simple the changes may be, are extremely hard to find afterwards.
This is exactly the basic idea of functions: You program the above mentioned search algorithm in general and thus have many advantages:
- you can make sure that the algorithm works correctly and from this point on you are sure that it works everywhere.
- you can execute the 10 lines of code in only one line and the program is therefore much clearer and better.
Functions basically work like this:
You give a function one or more values that it needs. In our case we would give it the corresponding array and the value we are looking for.
A function can have one (or more in Python) return values. In our case this would be e.g. the position of the searched value in the array.
The function gets the two required values, then executes the search algorithm and returns only the result.
In some programming languages you have to watch out how to pass values to functions (call by value, call by reference etc.), but this would lead too far at this point, so I will only talk about the basic function (call by value).
In Python there are extremely many prefabricated functions in libraries. To use them you have to import them. This works in different ways:
You can import the whole library, then you must call the function by libraryName.functionName():
You can import only one function from a library, then you can call it by just using its name:
You can import only one function from a library and give it a individual name: