Module 26: Importing Modules

Unlock pre-built code to power up your Python scripts!

📦 Opening the Toolbox

Imagine needing a specific tool, like a calculator or a random number generator. Instead of building it from scratch every time, Python lets you borrow pre-written code.

These collections of pre-written code are called modules. We use the import keyword to bring their functionality into our own programs. This is a core concept for efficient programming!

🛠️ Why Import? Think Toolboxes!

Importing is like grabbing the right tool for the job.

You Need Functionality

e.g., Calculate a square root or pick a random item.

➡️

Import a Module

Use import math or import random to get the toolbox.

➡️

Use its Tools

Call functions like math.sqrt() or random.randint().

Importing brings powerful, pre-tested tools directly into your code.

🧩 Benefits of Using Modules

Modules make programming smarter, not harder.

Reusability

Don't reinvent the wheel! Use code that others have written and tested. Saves time and reduces errors.

PC: Reusability

Abstraction

You can use a module's functions without needing to understand every detail of how they work internally. Focus on *what* it does, not *how*.

PC: Abstraction

Organization

Modules group related functions together, keeping code clean, manageable, and easier to understand.

Click on the cards above to reveal more!

⚙️ Modules in Action

Let's see how to import and use the `math` and `random` modules.

import math # Bring in the math module

number = 16
result = math.sqrt(number) # Use its sqrt function

print(f"The square root of {number} is {result}")
# Output: The square root of 16 is 4.0
import random # Bring in the random module

dice_roll = random.randint(1, 6) # Get random integer 1-6

print(f"You rolled a: {dice_roll}")
# Output: You rolled a: [some number between 1 and 6]

First, we use the importThe keyword to load a module. statement followed by the module name (e.g., math, random).

To use a function from an imported module, we type the module nameThe name of the imported module (e.g., math)., a dot ., and then the function nameThe specific tool/action from the module (e.g., sqrt). with parentheses ().

For example, math.sqrt(16) calls the `sqrt` function inside the `math` module.

Similarly, random.randint(1, 6) calls the `randint` function from the `random` module.

🧠 Quick Check!

Module 26 Theory Complete!

You've learned how to import and use modules – a key skill for writing efficient Python code! This relates strongly to Reusability and Abstraction.
Ready to practice? Head to the Practice Zone or challenge yourself with the Advanced Practice.