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.
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)
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.
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.