In python, modules are python program files that contain functions, classes or variables. Modules are useful to organize your code into different sections. In order to use a module, we need to import at the beginning of the code.
In order to import a module, we can use two types of statements: import statement or a from-import statement. With an import statement, we import to our code all the functionality of any python source file to our python code. The import module syntax is the following:
let’s create a python file to be used as our module file in the next example.
To call print_me() in python file, import that function from the source file and use the function normally.
In this example, we call a from “source_file” to import the print_me function, to use in our code.
There are many predefined modules in python, few of them are
The math module is a python module, which comes with python installation. Math module provides access to mathematical functions. There are numerous functions in math module and if you want to explore for yourself, you should read the official python document on this website (https://docs.python.org/3/library/math.html). Now, let me give you two common examples of the math module.
In the first example, we use sqrt() function, which calculates the square root of a number. In the second example, we use exp() function, which calculates the exponential of number.
The random module has different pseudo-random number generator functions. One of the commonly used examples when learning Python is the use of randint() function, which selects an integer number randomly from a specific range. Let’s see how can we use the randint() function: