Introduction to Computer Science/1.7: Importing New Powers (Modules)

1.7: Importing New Powers (Modules)



🎯 Learning Goals for This Page
  • Understand that a "module" is a library of pre-written Python code.
  • Use the import keyword to bring a module's functionality into your program.
  • Use constants (like math.pi) and functions (like math.sqrt) from an imported module.

Expanding Your Toolkit with Modules

So far, we've only used the "built-in" functions that come with Python by default, like print() and input(). But Python's real power comes from its vast collection of modules.

Think of a module as a specialized toolbox. If you need to do a specific type of work (like advanced math, generating random numbers, or building a game), you can import that toolbox into your program to use its tools.

The import Keyword

To use a module, you must first bring it into your file using the import keyword. This is almost always done at the very top of your program. To get access to Python's built-in math tools, we do this:

import math

Once you've imported the math module, you can access all of its tools using "dot notation": math.tool_name.


Live Example: The math Module

The math module gives us access to more accurate mathematical constants and more advanced functions. For example, instead of typing 3.14159 for pi, we can now use math.pi. It also gives us functions like math.sqrt() to find the square root of a number.

Click the Run ▶ button to see it work. Then, try changing the numbers! Can you find the square root of 81? Can you calculate the area of a circle with a radius of 25?

Python 3Initializing...
Loading code editor...
Program output will appear here...
The Tip of the Iceberg

The math module is just one of thousands of modules available in Python. There are modules for creating games (pygame), building websites (Flask, Django), analyzing data (pandas), and so much more. Learning to find and use modules is a key skill for any programmer.

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...