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.
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.
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.
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.
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.