Overview: Python Import Statement
Python provides reusable code through modules. Some modules are built into Python, while others can be created to organize functions, variables, classes, and other code.
To use a module in a program, Python provides the import statement. It lets one Python file use code from another module without copying it, making programs easier to organize and maintain.
This guide explains the Python import statement, its syntax, and how to import both built-in and user-defined modules.
Quick Navigation: Python Import Statement
Navigate through the sections below to learn the Python import statement, its syntax, module importing techniques, examples, and best practices.
- Introduction: What is the Python import Statement?
- Syntax: Python import Statement
- Importing Built-in Modules Using the import Statement
- Importing User-defined Modules Using the import Statement
- Accessing Module Members: Python import Statement
- Importing Multiple Modules Using the import Statement
- Importing Modules from Another Python File Using the ‘import’ Statement
- Common Errors: import Statement
- Best Practices: import Statement
- Key Takeaways: import Statement
Introduction: What is the Python import Statement?
The Python import statement loads a module into the current program. After importing a module, you can use its functions, variables, classes, and other members.
For example, the built-in math module provides common mathematical functions. Instead of writing these functions yourself, you can import the module and use them whenever needed.
Real-World Analogy
Imagine using a cookbook while preparing a meal. You do not rewrite every recipe—you simply open the book and use the recipe you need. The import statement works in a similar way by letting your program use code stored in another module.
Why Use the Python import Statement?
The import statement makes reusable code available whenever a program needs it.
- Reduces duplicate code.
- Keeps programs organized.
- Provides access to Python’s standard library.
- Allows custom modules to be reused.
- Makes large programs easier to manage.
💡 Tip: To learn Python modules from the basics through advanced topics, continue with the Python Modules Learning Path.
Syntax: Python import Statement
The import statement uses the import keyword followed by the module name.
import module_name
Syntax Components
| Part | Description |
|---|---|
import |
The Python keyword used to load a module. |
module_name |
The name of the built-in or user-defined module to import. |
How the Syntax Works
When Python executes an import statement, it loads the module so its members can be used in the program.
For example, after importing the math module, its sqrt() function can be accessed using dot notation:
import math
print(math.sqrt(25))
# Output
5.0
Code Explanation
math.sqrt(25) calls the sqrt() function from the math module. It returns the square root of 25, which is 5.0.
Note: The module name is used with dot notation to access its members after importing.
Importing Built-in Modules Using the import Statement
Python includes many built-in modules for common tasks such as mathematical calculations, random number generation, file handling, and working with dates and times.
After importing a module, its members are accessed using the dot (.) operator.
Example: Importing the math Module
import math
print(math.sqrt(64))
print(math.factorial(5))
#Output
8.0
120
Code Explanation
This program imports the built-in math module and calls its sqrt() and factorial() functions. The results are printed on separate lines.
Importing User-defined Modules Using the import Statement
You can also create your own modules to organize reusable functions, variables, and classes.
After importing a user-defined module, its members are accessed the same way as a built-in module.
Example: Importing User-defined Modules
calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
main.py
import calculator
print(calculator.add(20, 10))
print(calculator.subtract(20, 10))
# Output
30
10
Code Explanation
The calculator.py module contains the add() and subtract() functions. After importing the module, both functions are called using dot notation.
For beginners, keeping both files in the same directory is the simplest way for Python to locate the module.
Accessing Module Members: Python Import Statement
After importing a module, its members are accessed using dot notation.
Syntax
module_name.member_name
Example: Accessing Module Members
import math
print(math.ceil(8.2))
print(math.floor(8.9))
# Output
9
8
Code Explanation
math.ceil(8.2) returns 9, while math.floor(8.9) returns 8. Both functions are accessed using dot notation.
What Can Be Accessed from a Module?
Depending on how a module is designed, it may contain different types of members. The most common ones include:
- Functions – Perform specific tasks, such as mathematical calculations or file operations.
- Variables – Store values that can be reused throughout the program.
- Classes – Define blueprints for creating objects.
- Constants – Represent fixed values provided by the module.
Importing Multiple Modules Using the import Statement
A program can import more than one module. Each module provides different functionality.
The recommended approach is to write each import statement on a separate line because it keeps the code easier to read.
Example: Importing Multiple Modules
import math
import random
print(math.sqrt(81))
print(random.randint(1, 10))
# Sample Output (may vary)
9.0
7
Code Explanation
This program imports the math and random modules. The sqrt() function calculates the square root of 81, and randint() generates a random number between 1 and 10.
Importing Modules from Another Python File Using the import Statement
Modules make it easy to reuse code stored in another Python file. Instead of writing the same functions in multiple files, you can place them in one module and import them whenever needed.
The following example shows how modules are organized across separate Python files in a project.
Example Project Structure
project/
│
├── calculator.py
└── main.py
Consider the following project, where the calculator.py file contains reusable functions and the main.py file imports and uses them.
calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
The main.py file imports the module and uses its functions.
main.py
import calculator
print(calculator.add(15, 5))
print(calculator.multiply(15, 5))
# Output:
20
75
Code Explanation
The calculator.py module contains the add() and multiply() functions. The main.py file imports the module and calls both functions using dot notation.
Common Errors: import Statement
Beginners often make a few common mistakes while using the import statement. Understanding these errors makes them easier to fix.
Below are the most common ones:
The following sections explain each error and its solution.
1. ModuleNotFoundError
This error occurs when Python cannot locate the module that you are trying to import.
import calculator
Possible reasons include:
- The module file does not exist.
- The file name is incorrect.
- The module is located in a different folder.
- The required package has not been installed.
2. NameError
A NameError usually occurs when a module or one of its members is referenced incorrectly.
import math
print(sqrt(25))
# Output
NameError: name 'sqrt' is not defined
The correct way is:
import math
print(math.sqrt(25))
Since only the module was imported, the function must be accessed through the module name.
3. Common Typing Mistakes
Python is case-sensitive, so even small typing mistakes can result in errors.
Incorrect
Import math
Correct
import math
Similarly, importing Math instead of math or misspelling a module name will also cause errors.
Best Practices: import Statement
- Avoid using
from module import *because it can make code harder to understand. - Import only the modules that your program actually needs.
- Place import statements at the beginning of the file unless there is a specific reason not to.
- Use meaningful module names for your own modules.
- Avoid creating user-defined modules with the same names as Python’s built-in modules.
- Remove unused imports to keep the code clean.
Key Takeaways: import Statement
Here are the key points to remember about the Python import statement:
- The
importstatement allows a Python program to use code from another module. - You can import both built-in and user-defined modules.
- Module members are accessed using the dot (
.) operator. - Multiple modules can be imported within the same program.
- Understanding common import errors makes debugging much easier.
- Following good import practices improves code readability and maintainability.