First of all three important things about functions:
- A function is a block of code which only runs when it is called.
- You can pass data, known as parameters, into a function.
- A function can return data as a result.
In other words: A function helps you to approach a challenge you want to solve in a more efficient way with less error potential. Defining the content of a function once, you can easily apply it to different use cases as well and don’t have to write the code over and over again.
In the sense of soccer a function is like a rehearsed play, which can be repeated over and over again in different situations to solve a challenge.
The cool thing is, that there are already existing functions in Python. But before you can use them it is often the case, that you have to import them.
To import the whole library (in our example “math”) you can do this by libraryName.functionName():
You can import only one function from a library, then you can call it by just using its name:
And if you don’t like the default names of the funtions you can just assign your own names to them e.g. the one of your favorite soccer player:
All the examples shown above will return the value of pi. One more thing:
It is important to understand what the “return”-Statement does within the functions and how it can be seperated from the “print”-Statement. The best resource I could find on the internet on this was this video: