In the last post, we used functions to do things for us. We used the
int function to turn decimal numbers into integers (ie 5.6 was turned in to 5), and the
abs function to remove the negative parts of a number (ie -3 was turned into 3).
So, what is a function?
A function is just a small program which can be reused many times. For example, some other programmer wrote code to print to the terminal. This other programmer was kind enough to give make it available for us to use in our code. Now we can write to terminal simply by utilizing the built in
How to Use a Function
In Python, the way to run a function (also known as calling a function) is to write the name of the function, followed by parentheses.
Sometimes the function may need additional information in order to run. This data is provided to the function between the opening and closing parenthesis. The data can be any information (like a number or text). For instance, the
abs function requires a number on which to perform the calculation. So, we call
abs by writing
abs(-5). The value is then used internally to the function, and (if appropriate) the result is sent back to us.
The information that is sent back to us is called the return value. For instance, we say that
abs(-17) returns the value 17. We can use this return value inline or capture and store it in a variable, which we will discuss in the next lesson.
Built in Functions
Some functions in Python are built-in. These are available to us no matter what. Other functions are part of other libraries or modules; we need to add them into our programs before we can use them.
Later, you will learn how to make functions out of your own code. For now, we’ll take a quick look at some of the built-in functions in Python.
You can find more built-in functions and their explanations in the Python 3 documentation.
You should be more familiar with what a function is and why it is useful. It allows a piece of code to be called and reused multiple times without the need to re-write or copy/paste. We also learned how to pass data to a function as arguments and how to get results back as return values.
Next time, we’ll learn about storing data in variables while your program is running.