In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Python’s import statement is the most common way to bring in external functionality, but there are multiple ways to do it.
Importing a Module in Python
The most common way to use a module is by importing it with the import statement. This allows access to all the functions and variables defined in the module. Example:
Python
import math
pie = math.pi
print("The value of pi is:", pie)
OutputThe value of pi is: 3.141592653589793
Explanation:
- math module is imported using import math.
- We access the constant pi using math.pi and then the value is printed as part of a formatted string.
Importing Specific Functions
Instead of importing the entire module, we can import only the functions or variables we need using the from keyword. This makes the code cleaner and avoids unnecessary imports.
Python
from math import pi
print(pi)
Explanation:
- from math import pi imports only the pi constant, so we can use it directly without math. prefix.
- This reduces unnecessary module overhead when only specific functions or constants are needed.
Importing Built-in Modules
Python provides many built-in modules that can be imported directly without installation. These modules offer ready-to-use functions for various tasks, such as random number generation, math operations and file handling.
Python
import random
# Generate a random number between 1 and 10
res = random.randint(1, 10)
print("Random Number:", res)
Explanation:
- import random brings in Python's built-in random module.
- random.randint(1, 10) generates a random integer between 1 and 10.
Importing Modules with Aliases
To make code more readable and concise, we can assign an alias to a module using the as keyword. This is especially useful when working with long module names.
Python
import math as m
# Use the alias to call a function
result = m.sqrt(25)
print("Square root of 25:", result)
OutputSquare root of 25: 5.0
Explanation:
- import math as m imports the math module and assigns it the alias m.
- m.sqrt(25) calls the square root function using the alias.
Importing Everything from a Module (*)
Instead of importing specific functions, we can import all functions and variables from a module using the * symbol. This allows direct access to all module contents without prefixing them with the module name.
Python
from math import *
print(pi) # Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output3.141592653589793
720
Explanation:
- from math import * imports all functions and constants from the math module.
- pi and factorial(6) are accessed directly without using math. as a prefix.
- While convenient, this method is not recommended in larger programs as it can lead to conflicts with existing variables and functions.
Handling Import Errors in Python
When importing a module that doesn’t exist or isn't installed, Python raises an ImportError. To prevent this, we can handle such cases using try-except blocks.
Python
try:
import mathematics # Incorrect module name
print(mathematics.pi)
except ImportError:
print("Module not found! Please check the module name or install it if necessary.")
Output3.141592653589793
720
Explanation:
- try block attempts to import a module, if the module is missing or misspelled, Python raises an ImportError.
- The except block catches the error and displays a user-friendly message instead of crashing the program.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read