Skip to main content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 1.14 Importing modules

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Modules

Modules can be seen as bundles of functions that we can call in so that we can use them in our code, without coding from scratch. To manipulate data better, we sometimes need access to other functions and libraries.

Importing modules

Importing modules

To use the functions in modules and libraries, we have to first import them. For this guide page, we will use the library called  random  as an example. 

syntax

import random


After importing the  random  module, its functions and methods are available for use in our code.

In this example, we will be using the  randint()  method. The  randint()  method takes in the inputs of 2 numbers and returns a random integer in between. 

To use the  randint()  method, we first have to state the module that it is from, then the method.

Syntax

random.randint()
 

Example

Here, we want Python to give us a random number between 1 and 6. 

Module naming shortcuts

We can shorten our codes by shortening the names of the modules. To shorten the codes, we can do the following, where  rd  is set by you. 

Syntax

import random as rd

 rd  is the naming convention for random. Hypothetically we can name it anything we want.

import random as rd

myRandomNum = rd.randint(1,6)
print(myRandomNum)

 

Other modules we can import in the future

We can also define our own functions and import these self-made functions for future codes we do in the future. This will be covered in Unit 2.

There are many other useful modules such as pandas and numpy that we can explore as we learn. We will cover them in detail in our other units 3 and 4.

Exercises

1. Import random and create a shortcut for it. Generate a random number between 5 to 25.

2. Import random and try its  choice()  method. First, create a list. Second, ask python to print any element from your list using the  choice()  method.