Python has build-in many functions, but we can still access even more functions when we “import” a “module”. A module works like a library. Since python is open source, more and more developers are working on improving the existing modules and developing new modules. What’s more, we can even make our own modules too. It’s very useful for reusing our codes and simplifying the development procedure.
Most of the modules will not be preinstalled in Python. When we are trying to access it, we need to “import” them first. The format for importing a module is:
import <name of module> (as <nickname>)To use the function in the modules that we import, we can simply use <name of module>.<name of function>.
The most common used modules in Python would be “math” and “random” modules. The “math” module provides a lot of math function like sin, cos, log, and exp functions that are not defined in Python. And “random” module provides random functions that can interact with not only numbers, but also lists.
# use of math module
import math
# get the value of pi in the math module
>>> print(math.pi)
3.141592653589793
# use sin() function
>>> print(math.sin(20))
0.9129452507276277
# use log() function
>>> print(math.log(3.45))
1.2383742310432684
# use sqrt() function
>>> print(math.sqrt(36))
6.0
# there are more functions in the math module
# floor(): return the floor of x as an Integral
# ceil(): return the ceiling of x as an Integral
# gcd(): Greatest Common Divisor
# fabs(): return the absolute value of the float x
# use of random module
import random
# random float from [0,1)
random.random()
# random integer from [start, end]
random.randint(start, end) # include both start and end points
# random integer using "range" format
random.randrange(start, end) # not include end point
# randomly choose from a list
random.choice(list)
# randomly shuffle a list
random.shuffle(list)
# there are more functions in the random module about some distribution,
# such as normal distribution, gaussian distributionSometimes in our program, we can write our own helper functions in some .py file. These .py files can be our own “module”s. In order to use them, we can write import <name of file>. If we only want to use one or some of the functions of the module, we can only import the functions that we need. We can also use “*” to import all functions, although this is rarely used.
# for example, we only want to use the sin() function in math module
>>> from math import sin
# in this case, we can use the function directly
>>> print(sin(20))
0.9129452507276277
# we can also set a "nickname" for the module
# so that we don't need to type the full name of the module
>>> import random as rd
>>> print(rd.random())
0.8025982517989496
# the "nickname" also works for functions
>>> from random import randrange as rr
>>> print(rr(1, 10))
1