Modules

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.

Importing module

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:

 

import function1, function, … function n

from file_module import function1


let’s create a python file to be used as our module file in the next example.

 

def print_me():
    print("Hello world")


To call print_me() in python file, import that function from the source file and use the function normally.

 

from source_file import print_me
print_me()

 

Output: I'm printing from source_file.py


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


Math module

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.

 

import math
print(math.sqrt(12))

 

Output: 3.4641016151377544

 

import math
print(math.exp(10))

 

Output: 22026.465794806718


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.

Random module

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:

 

import random
print(random.randint(1,100))

 

Output: 62(It vary for every execution)

 

Related Tutorials