6 1 Importing Modules Explained
Key Concepts
Importing modules in Python allows you to use code from other files or libraries. The key concepts include:
- Importing Standard Modules
- Importing Specific Functions
- Aliasing Modules
- Importing from Packages
- Creating and Importing Custom Modules
1. Importing Standard Modules
Python comes with a set of standard modules that provide additional functionality. You can import these modules using the import
statement.
Example:
import math result = math.sqrt(16) print(result) # Output: 4.0
Analogy: Think of a toolbox where you can pick a specific tool (module) to perform a task (function).
2. Importing Specific Functions
Instead of importing the entire module, you can import specific functions from a module using the from ... import ...
statement.
Example:
from math import sqrt result = sqrt(16) print(result) # Output: 4.0
Analogy: Think of a toolbox where you only take the specific tool (function) you need, not the entire toolbox.
3. Aliasing Modules
You can give a module or function an alias using the as
keyword to make it easier to reference in your code.
Example:
import math as m result = m.sqrt(16) print(result) # Output: 4.0
Analogy: Think of a toolbox where you label a tool (module) with a shorter name for easier access.
4. Importing from Packages
Packages are collections of modules. You can import modules from packages using the from ... import ...
statement.
Example:
from datetime import datetime now = datetime.now() print(now) # Output: Current date and time
Analogy: Think of a toolbox (package) containing multiple smaller toolboxes (modules).
5. Creating and Importing Custom Modules
You can create your own modules by writing Python code in a file and then importing it into another script.
Example:
Create a file named mymodule.py
with the following content:
# mymodule.py def greet(name): return f"Hello, {name}!"
Then, in another script, import and use the custom module:
import mymodule message = mymodule.greet("Alice") print(message) # Output: Hello, Alice!
Analogy: Think of creating your own toolbox (module) and using it in your projects.
Putting It All Together
By understanding and using these import techniques effectively, you can leverage existing code and create modular, reusable Python programs.
Example:
import math as m from datetime import datetime import mymodule result = m.sqrt(16) print(result) # Output: 4.0 now = datetime.now() print(now) # Output: Current date and time message = mymodule.greet("Alice") print(message) # Output: Hello, Alice!