Module 10: Study Guide
Review key concepts from Modules & Imports
Key Terms
Module: A Python file (.py) containing functions, classes, and variables that can be reused through importing.
Standard Library: The collection of modules that come built into Python (math, random, datetime, etc.).
pip: Python's package installer for downloading and installing third-party packages from PyPI.
PyPI: Python Package Index - an online repository of over 400,000 community-created Python packages.
Virtual Environment: An isolated Python environment where packages are installed separately from the system Python.
Dot Notation: Using
module.function() to access items inside a module.Alias: A shorter name for a module created with
import module as alias.Lesson 1: Built-in Modules
What to Know
- The math module provides
sqrt(),ceil(),floor(), and the constantpi ceil()rounds up,floor()rounds down- The random module provides
randint(),choice(), andshuffle() shuffle()modifies the list in place and returnsNone- The datetime module provides
now()for current date/time andstrftime()for formatting
Lesson 2: Import Statements
Three Import Styles
import math # Use as: math.sqrt(16) from math import sqrt # Use as: sqrt(16) import math as m # Use as: m.sqrt(16)
What to Know
- Avoid
from module import *- it causes naming conflicts - Python only runs module code once even with multiple imports
- Place imports at the top of your file in this order: standard library, third-party, your own modules
Lesson 3: Installing Packages
What to Know
- pip commands run in the terminal, not inside Python
pip install packagedownloads and installs a packagerequirements.txtlists project dependenciespip freeze > requirements.txtsaves current packages- Virtual environments isolate project dependencies
python -m venv myenvcreates a virtual environment
Lesson 4: Organizing Code
What to Know
- Any .py file can be imported as a module
if __name__ == "__main__":runs code only when file is executed directly- When a file is imported,
__name__is set to the module name - Group related functions in the same module
- Use descriptive file names and add docstrings
Review Questions
1. What is the difference between import math and from math import sqrt?
2. Why should you avoid from module import *?
3. What happens when Python encounters an import statement for a module that was already imported?
4. What is the purpose of if __name__ == "__main__":?
5. When would you use a virtual environment?
6. What is the difference between pip install and import?
Common Mistakes to Avoid
- Forgetting to import a module before using it
- Using
math.sqrt()afterfrom math import sqrt(use justsqrt()) - Running pip commands inside a Python file instead of the terminal
- Naming your file the same as a module (e.g.,
math.pyconflicts with the built-in math module) - Forgetting that
random.shuffle()returns None - Using parentheses with
math.pi(it is a constant, not a function)