×

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

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

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

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.