Python is a versatile piece of kit straight out of the box. By itself it can do just about anything, from simple calculations, to automating a Twitter account, through to being a robot’s ‘brain’. However, we can make most jobs that we will do in Python a lot easier by using modules – sort of like Python add-on kits. These modules create groups of functions that make tasks quicker to write and perform. Without them, we’d have to write horribly lengthy code once we got beyond simple tasks.
To use a module, you must first install it onto your machine and then import it into any code that will use it. This article will take you through both steps:
If you are using an Anaconda install of Python, the interface in Anaconda Navigator should have most modules that you are looking for available. Simply ensure that it is ticked and installed on your environment page.
If you are using another type of Python install, simply open up the terminal (your machine’s terminal, not Python) and run ‘pip install [MODULE NAME]’. Any issues that you run into at this point will be well-documented on Stack Overflow and Google, so give those a look if so.
With our module installed on your machine and ready to go, we just need to import it. For this example, we’ll import the ‘math’ module, to give us access to the value for pi. Let’s see what happens without importing the module:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-9493078a23d9> in <module>() ----> 1 math.pi() NameError: name 'math' is not defined
import math print(math.pi)
Without importing the math module, Python obviously has no idea what it is. Once we import it, away we go!
With some modules, you will notice a convention to import them and give them different names. This is done with the ‘as’ keyword after our import:
import pandas as pd import numpy as np np.arange(0,10,2)
array([0, 2, 4, 6, 8])
Harvard’s Introduction to Computer Science course opens with the discussion that we are ‘standing on the shoulders of giants’, highlighting the work of programmers before us that have built languages, modules and tools that allow us to be more productive.The Python community is a perfect example of this, with thousands of modules available to us that make complex tasks a bit more manageable.