Chapter 1: The Basics / Lesson 4

Modules and Imports

7 min ยท The Basics

What are Modules?

Modules are Python files containing functions, classes, and variables that you can reuse in your code. Python comes with a vast standard library of built-in modules that provide ready-to-use functionality for common tasks.

Using modules allows you to organize code into logical units, reuse code across projects, and leverage the work of others. Instead of writing everything from scratch, you can import modules and use their functionality.

imports.py
# Import a module to access its functions and variables import math # Use module_name.function_name() to call functions print(math.pi) # 3.141592653589793 print(math.sqrt(16)) # 4.0 print(math.pow(2, 3)) # 8.0

Import Styles

Python offers several ways to import modules. Each has its use case:

import_styles.py
# Style 1: Import entire module (most common) import math print(math.sqrt(16)) # Use math.function_name # Style 2: Import specific items from math import pi, sqrt print(pi) # Use directly: pi print(sqrt(16)) # Use directly: sqrt() # Style 3: Import with alias (useful for long module names) import math as m print(m.pi) # Use alias: m.function_name # Style 4: Import all (NOT RECOMMENDED - pollutes namespace) # from math import * # print(sqrt(16)) # Works but can cause name conflicts

Recommended Import Style

๐Ÿ’ก Best Practice

Use import module_name for most cases. It's clear where functions come from and avoids name conflicts. Only use from module import item when you need a specific function frequently.

โš ๏ธ Avoid Wildcard Imports

Never use from module import *. It makes code harder to read and can cause unexpected conflicts with your variable names.

Common Built-in Modules

Python's standard library includes hundreds of modules. Here are some of the most commonly used ones:

  • math โ€” Mathematical functions and constants (sqrt, sin, cos, pi, e)
  • random โ€” Random number generation (randint, choice, shuffle)
  • datetime โ€” Date and time handling (date, time, datetime)
  • os โ€” Operating system interface (file paths, environment variables)
  • json โ€” JSON encoding and decoding (loads, dumps)
  • sys โ€” System-specific parameters and functions
  • re โ€” Regular expressions for pattern matching
  • collections โ€” Specialized container datatypes

Examples of Common Modules

Let's see some practical examples of using different modules:

module_examples.py
# Math module import math print(math.sqrt(25)) # 5.0 print(math.ceil(4.2)) # 5 print(math.floor(4.8)) # 4 # Random module import random print(random.randint(1, 10)) # Random number between 1 and 10 print(random.choice(["apple", "banana", "cherry"])) # Datetime module from datetime import datetime now = datetime.now() print(now) # Current date and time

Importing Multiple Modules

You can import multiple modules in your program. It's common to group imports at the top of your file:

multiple_imports.py
# Standard library imports (Python built-in) import math import random from datetime import datetime # Use them in your code radius = 5 area = math.pi * radius ** 2 random_num = random.randint(1, 100) current_time = datetime.now() print(f"Area: {area}") print(f"Random: {random_num}") print(f"Time: {current_time}")

Module Organization

Python conventions recommend organizing imports in this order:

import_order.py
# 1. Standard library imports import math import os # 2. Third-party library imports # import requests # import numpy # 3. Local application imports # from my_module import my_function # Then your code starts here... print("Program starts")

Checking Available Functions

You can see what's available in a module using the dir() function:

exploring_modules.py
import math # See all available items in the module # print(dir(math)) # Shows all functions and constants # Access module documentation # help(math.sqrt) # Shows help for sqrt function # Common math module items print(math.pi) # 3.141592653589793 print(math.e) # 2.718281828459045 print(math.sqrt(16)) # 4.0 print(math.sin(math.pi/2)) # 1.0

Module vs Package

๐Ÿ“ Module vs Package

Module: A single Python file containing code (e.g., math.py)

Package: A directory containing multiple modules (e.g., datetime package has date, time modules)

๐ŸŽ‰

Lesson Complete!

Great work! Continue to the next lesson.

main.py
๐Ÿ“ค Output
Click "Run" to execute...