Importing Modules in Python

ScopeModules

One of Python's greatest strengths is its ability to reuse code. Instead of writing everything from scratch, you can import functions, classes, and variables from other Python files or from the huge built-in standard library.

This lesson will teach you everything about importing: the different ways to do it, how to use popular standard library modules, best practices, and the special __name__ == "__main__" trick to make your files both importable and runnable.

By the end, you'll feel confident bringing in code from anywhere – making your programs shorter, cleaner, and more powerful.

Why Do We Import?

Imagine you write a useful function for calculating averages. You don't want to copy-paste it into every new program. Instead, you save it in a separate file and import it when needed.

Python also comes with thousands of ready-made tools (standard library) – math calculations, random numbers, date handling, and much more. Importing gives you access to all of this for free.

Basic Import Syntax

The simplest way: import module_name

This loads the entire module, and you access items with dot notation.

The math module is part of Python's standard library – no installation needed!

Import Specific Items with 'from ... import'

If you only need certain functions, import them directly – no need for dot notation.

Using Aliases with 'as'

Give a module or item a shorter name for convenience.

Popular Standard Library Modules

Here are some commonly used modules you'll import often:

  • math – mathematical functions and constants
  • random – generate random numbers and choices
  • datetime – work with dates and times
  • os – interact with the operating system
  • sys – system-specific parameters and functions

The Special __name__ == "__main__" Guard

When you run a Python file directly, __name__ is "__main__". When imported, it's the module name.

This lets you write code that runs only when the file is executed directly – perfect for tests or examples.

Best Practices for Imports

  • Place imports at the top of the file
  • Group: standard library → third-party → local
  • One module per import line (clearer)
  • Avoid 'from module import *' – hides what is imported
  • Use meaningful aliases when helpful

Quick Quiz

We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.

✨ Ask Lara — your AI study partner

Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.


Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.