Python
Module 8: Python Modules and PackagesBeginner15 min read

Importing & Creating Modules

Structure modular code across multiple files and understand import statements.

Key Takeaways & Core Concepts
  • is simply a Python file (.py) containing code—functions, classes, or variables—that you want to include in your application.
  • is a collection of modules within a directory containing an __init__.py file.

Importing & Creating Modules

### Python Modules & Packages

A module is simply a Python file (.py) containing code—functions, classes, or variables—that you want to include in your application.

A package is a collection of modules within a directory containing an __init__.py file.

PYTHON Code Example
1# Importing built-in modules
2import math
3import random
4from datetime import datetime, timedelta
5
6print("Square root of 64:", math.isqrt(64))
7print("Current date:", datetime.now().strftime("%Y-%m-%d"))
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
7 lines

#### The __name__ == '__main__' Idiom When a Python file is run directly, Python sets __name__ to "__main__". When imported as a module into another script, __name__ is set to the module's filename:

PYTHON Code Example
1def main():
2 print("Executed directly as entry point")
3
4if __name__ == "__main__":
5 main()
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines
Math Module Constants and Functions
1import math
2
3radius = 5
4area = math.pi * (radius ** 2)
5print(f"Area of circle with radius {radius}: {area:.2f}")
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines
Note: math.pi provides high-precision mathematical pi constant.
Practice & AssessmentPython Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)