×

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 Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.