An object-based programming language is structured around two major concepts: objects and functions. An object is everything we create in a work session using a programming language such as Python. Functions allow us to assign one or more actions to these objects. Let’s learn how to create a function.
Some words about functions in Python
- 1.
The built-in functions that are part of Python and are loaded automatically when we run Python
- 2.
The functions we can build and use (user defined)
A function is a piece of code that performs one or more operations on an object and returns an output result. Functions are especially useful when we have to do the same thing over multiple objects. We can do this without repeating the same line of code several times.
The two types of functions are also supported by those in the many libraries available for installation on Python. Whenever we need a particular function (or a package, that is a family of functions), we can install it and use it. Anaconda does not allow us to install many of the packages we need because they already exist in the suite.
In any case, the exact wording for installing a package is always included in the official documentation of the package itself.
Some Predefined Built-in Functions
It is important to remember that when bracketing an object (such as a list, tuple, dictionary, and so on) using the dir() function, we get a list of actions we can assign to that particular object.
When we work with packages and functions written by other data scientists, it is useful to obtain information about their functions and their parameters. Let’s see how to do this.
Obtain Function Information
You can find the built-in functions for Python 2.7 at https://docs.python.org/2/library/functions.html . You can find the built-in features for version 3 at https://docs.python.org/3/library/functions.html .
Create Your Own Functions
To help us see the path taken by one of our functions, we can use online tools such as Python Tutor ( http://pythontutor.com/ ).
Save and run Your Own Modules and Files
The Python shell is convenient for testing on the fly, but for a complex script, it is always better to write it using an editor and then run it that way, or copy the script and run it in the Python shell.
Summary
Writing functions is a very important task for a data scientist. Languages such as R have a large number of packages and functions for every statistical need. With Python, however, we often need to write our functions, as detailed in this chapter. In Chapter 5, we look at more tools that we can use to build a useful function.