Importing Modules in Python
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
Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.
✨ Frag Lara — deine KI-Lernpartnerin
Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.
Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.

