Module 3 Lesson 7: Importing Modules
Don't reinvent the wheel. Learn how to use Python's 'import' system to tap into thousands of pre-written functions and libraries.
Module 3 Lesson 7: Importing Modules
Python's greatest strength is its massive ecosystem. You don't have to write your own algorithm for calculating the square root or generating a random number—someone else already did! We access these pre-written blocks of code using Modules and the import statement.
Lesson Overview
In this lesson, we will cover:
- What is a Module?: A single file containing code.
- Basic
import: Bringing in a whole toolbox. - Selective Imports: Using
from ... import. - Aliasing: Giving a module a nickname with
as.
1. What is a Module?
A module is simply a Python file (.py) that contains functions and variables. When you import a module, you are effectively copy-pasting its code into your own project so you can use its features.
2. Basic import
The simplest way is to import the entire module. You then access its functions using the "Dot Notation" (module.function).
import math
result = math.sqrt(64)
print(result) # Output: 8.0
3. Selective Imports (from ... import)
If you only need one or two specific tools, you can import them directly. This allows you to use the function name without the module prefix.
from math import pi, sin
print(pi) # Output: 3.14159...
print(sin(0)) # Output: 0.0
4. Aliasing (Nicknames)
Sometimes module names are long, or you want to avoid clashes with your own functions. You can use the as keyword to give it a nickname.
import datetime as dt
now = dt.datetime.now()
print(now)
Common Standard Library Modules:
random: For generating random numbers and choices.os: For interacting with your computer's folders and files.json: For working with data formats.time: For adding delays (time.sleep) or timing your code.
Practice Exercise: The Random Math Tool
Create a file named random_tools.py.
- Import the
randommodule. - Import the
mathmodule using an aliasm. - Generate a random integer between 1 and 100.
- Calculate the square root of that random number using
m.sqrt(). - Print a message:
"The random number was [X] and its square root is [Y]."
Quick Knowledge Check
- What is the main difference between
import mathandfrom math import sqrt? - What does the
askeyword do in an import statement? - Name three modules that come pre-installed with Python.
- Why is it better to use a module for math than to write your own square root logic?
Key Takeaways
- Modules are external files containing functions you can use.
- Use
importfor the whole module andfrom ... importfor specific parts. - Aliasing (
as) makes code cleaner and prevents name conflicts. - The "Standard Library" is a collection of modules that come free with Python.
What’s Next?
If you can import Python's built-in modules, you can also import your own! In Lesson 8, we’ll learn how to create Custom Modules to organize your growing programs!