×

Import Module in Python

In this article, you will learn everything about “ Import ” in Python.

Modules in python that are already created can be accessed and used in another code by importing the file or the function using " import ". Not only by using " import ", but there are also many other ways that help us to access the functions of another code. But, the " import " is used in order to carry out the processes easily and efficiently.

The syntax for using " import ":

# syntax for using import
import module_name
# the name of the module that is supposed to be 
# inserted must be mentioned  

The function " __import__() " is used and called immediately after the import is used and then searches for the module that is specified within the manageable and reachable scope. The function finally returns the value that the desired module consists of, and then it displays the value through an output of the code into which the module is imported.

What if the mentioned module does not exist?

If any randomly named module is given and asked for import, the Python application searches for the module with the mentioned name. After searching for the module, it shows an error representing the absence of the module with that specific name in your system. Let us understand this concept through the example given below.

Example:

# let us import the module " hello " which is not existing 
# on my pc and find out what happens
import hello
# let us give a print statement to find the error
print(hello.hi)

The output of the program:

Traceback (most recent call last):
  File "d:\downloads hdd\Java vs code programs\math.python.py", line 3, in <module>
    import hello
ModuleNotFoundError: No module named 'hello'

Let us understand the basic operations that can be performed using “ import ” with the following examples:

Example 1:

# let us import the math module and find the value of Euler's number
import math
# assign the value to a variable
a = math.e
# print the value of the variable to which the value of Euler’s # number is assigned
print("The value of Euler's number is: ")
print(a)

The output of the above example program:

The value of Euler's number is: 
2.718281828459045

Example 2:

# let us import the math module and find the value of pi
import math
# assign the value to a variable
a = math.pi
# print the value of the variable to which the value of pi is 
# assigned
print("The value of pi is: ")
print(a)

The output of the above example program:

The value of pi is: 
3.141592653589793

Example 3:

# let us import the math module and find the factorial of the given # number
import math
# assign the value to a variable
b = 10
a = math.factorial(b)
# print the value of the variable to which the factorial of 10 # is assigned
print("The factorial of the number 10 is: ")
print(a)

The output of the above example program:

The factorial of the number 10 is: 
3628800

In the programs that are discussed above, we have imported the entire module but just accessed the value of “ Euler’s number ” in the first program, the value of “ pi ” in the second program, whereas the " factorial " of the number " 10 " in the third program. Such type of accessing can be avoided, and only the required members of the module can be brought up into the program. Let us understand this from the upcoming statements.

The values of Euler’s number, Pi, and calculation of factorial can be retrieved by just importing the members of the " math " module, which supports “ Euler’s number ”, " factorial", and " Pi " respectively.

The function “ __import__().membername ” is called by the object while implementing this concept.

The syntax for importing desired members from a module:

# let us import desired members from the module they belong to
from module_name import member_name

If the module is imported in this way, only the members that are mentioned within the program will be imported from the module, and the rest of the members that belong to the module will just remain unimported. Let us implement this concept in the examples that are discussed above and verify the output for equality.

Example 4 ( Importing only Euler’s number member and mirroring Example 1 ):

# let us import e from the math module and find the value of 
# Euler’s Number
from math import e
# assign the value to a variable
a = e
# print the value of the variable to which the value of Euler’s # number is assigned


print("The value of Euler's number is: ")
print(a)

The output of the above example program:

The value of Euler's number is: 
2.718281828459045

Example 5 ( Importing only pi member and mirroring Example 2 ):

# let us import pi member from the math module and find the 
# value of pi
from math import pi
# assign the value to a variable
a = pi
# print the value of the variable to which the value of pi is 
# assigned
print("The value of pi is: ")
print(a)

The output of the above example program:

The value of pi is: 
3.141592653589793

Example 6 ( Importing only the factorial member and mirroring Example 3 ):

# let us import the factorial member from the math module and 
# find the factorial of a given number
from math import factorial
# assign the value to a variable
b = 10
a = factorial(b)
# print the value of the variable to which the factorial of 10 # is assigned
print("The factorial of the number 10 is: ")
print(a)

The output of the above example program:

The factorial of the number 10 is: 
3628800

We have followed the same procedure that has been followed in the corresponding examples, but there are two differences between the programs. The first one shows that we have imported just the desired member out of the entire module, and the second one shows that we have not mentioned " math.pi " or " math.e " or “ math.factorial ” while assigning the value to the variable. As we have already mentioned the main member and imported it in the initial step, we need not specify the “ math.module_name ” within the code body again.

How can we import all the constants and functions of the module without importing it fully?

The syntax for importing all the constants and functions of the module:

# syntax for importing all the constants and functions of the 
# module
from module_name import *
# the name of the module that is supposed to be 
# inserted must be mentioned, and " * " indicates " all "  

The above syntax represents how to import all the constants and functions that are embedded in a particular module without completely importing it. Let us work on a few examples that demonstrate this mechanism.

Example 7:

# let us import all the constants and functions of the 
# module “ math ” and find out the value of “ pi ”
from math import *
# print the value of pi 
print('The value of pi is: ')
print(pi)

The output of the program:

The value of pi is: 
3.141592653589793

Example 7:

# let us import all the constants and functions of the 
# module “ math ” and find out the factorial of “ 10 ”
from math import *
# print the value of factorial of “ 10 ” 
print('The factorial of 10 is ')
print(factorial(10))

The output of the program:

The factorial of 10 is 
3628800

Instead of writing these two types of different concepts as two programs, we can merge both concepts and write them within a single program. Let us discuss this concept through another example.

Example 8:

# let us import all the constants and functions of the 
# module “ math ” and find out the value of “ pi ” and the 
# “ factorial of 10 ”
from math import *
# print the value of pi 
print('The value of pi is: ')
print(pi)
# print the value of factorial of “ 10 ” 
print('The factorial of 10 is ')
print(factorial(10))

The output of the program:

The value of pi is: 
3.141592653589793
The factorial of 10 is 
3628800

Out of all these methods, the best one and the most efficient one that can be used is the last method. The reason is that this method enables all the features, which include constants and functions that the module consists of, and gives access to those without importing the module completely. This quality makes this method more efficient.


Related Topics

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.