> ## Documentation Index
> Fetch the complete documentation index at: https://python4ai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Working with Built-in Modules

> Learn to use Python's built-in standard library modules (math, random, datetime, os)

## Using Built-in Modules

Python comes with a rich set of built-in modules called the **Standard Library** that are ready to use immediately without installing anything from the internet. This design philosophy is often referred to as "batteries included."

## Understanding the Terminology

Let's clarify what these terms mean:

* **Module**: A single Python file containing code (like `math.py`).
* **Package**: A directory (folder) containing multiple modules and an `__init__.py` file.
* **Function**: A reusable block of code that performs a specific action (like `sqrt()`).
* **Class**: A template/blueprint for creating objects (we'll cover this later).

Think of it like this:

* A **module** is like a toolbox.
* A **package** is like a garage containing multiple toolboxes.
* A **function** is like a specific tool (a hammer or a screwdriver).
* A **class** is like a blueprint for building custom tools.

## Import Patterns Explained

To use a module, you must first import it. The two most common ways to import a module are:

```python theme={null}
# Pattern 1: Import the whole module
import math
# Now you access functions using the module name: math.sqrt(16)

# Pattern 2: Import specific items from a module
from math import sqrt, pi
# Now you can use the function directly: sqrt(16)
```

What's happening:

* `import math` brings the entire math toolbox into your script.
* `from math import sqrt` reaches into the math toolbox and pulls out only the `sqrt` tool.

***

## Python's Standard Library: Common Built-in Modules

Let's look at four of the most commonly used standard library modules: `math`, `random`, `datetime`, and `os`.

### 1. The `math` Module

The `math` module provides access to mathematical functions for trigonometric, logarithmic, and rounding operations.

```python theme={null}
import math

# Constants
print(math.pi)        # 3.141592653589793 (Ratio of circle's circumference to diameter)
print(math.e)         # 2.718281828459045 (Euler's number)

# Rounding Functions
print(math.ceil(4.2))   # 5 (Rounds UP to nearest integer)
print(math.floor(4.8))  # 4 (Rounds DOWN to nearest integer)

# Power and Roots
print(math.sqrt(16))    # 4.0 (Square root - always returns a float)
print(math.pow(2, 3))   # 8.0 (2 raised to power of 3, equivalent to 2 ** 3)

# Trigonometry (Angles must be in radians)
radians_90 = math.radians(90)
print(math.sin(radians_90))  # 1.0
```

<Tip>
  Remember that `math.sqrt()` always returns a floating-point number (e.g., `4.0`), whereas operators like `**` or functions like `math.floor()` return integers depending on their input.
</Tip>

### 2. The `random` Module

The `random` module provides tools to generate pseudo-random numbers and make random selections from collections.

```python theme={null}
import random

# Generating random numbers
print(random.random())          # Generates a random float between 0.0 and 1.0 (exclusive)
print(random.randint(1, 10))    # Generates a random integer between 1 and 10 (inclusive)
print(random.uniform(1.5, 5.5))  # Generates a random float between 1.5 and 5.5

# Selecting from a list
fruits = ["apple", "banana", "cherry", "date"]
print(random.choice(fruits))    # Randomly picks one item (e.g., "banana")

# Sampling multiple items (2 unique items without replacement)
print(random.sample(fruits, 2)) # e.g., ["cherry", "apple"]

# Shuffling a list in-place
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)                  # The list is now reordered randomly (e.g., [3, 5, 1, 4, 2])
```

<Warning>
  **Security Warning:** The `random` module is **not** cryptographically secure. For security-sensitive applications (such as password generation or security tokens), use Python's built-in `secrets` module instead.
</Warning>

### 3. The `datetime` Module

The `datetime` module offers classes for manipulating dates and times in both simple and complex ways.

```python theme={null}
import datetime

# Getting current Date and Time
today = datetime.date.today()
print(today)                    # Current date: YYYY-MM-DD (e.g., 2026-07-19)

now = datetime.datetime.now()
print(now)                      # Current date and time: YYYY-MM-DD HH:MM:SS.mmmmmm

# Creating specific dates
birthday = datetime.date(1995, 10, 25)
print(birthday.year)            # 1995

# Date Arithmetic (using timedelta)
ten_days_later = today + datetime.timedelta(days=10)
print(ten_days_later)

# Calculate difference between two dates
delta = today - birthday
print(delta.days)               # Total days elapsed since birthday
```

#### Formatting Dates as Strings (`strftime`)

To convert a datetime object into a readable string format, use `.strftime()` (string format time):

```python theme={null}
now = datetime.datetime.now()
# %Y = Year, %m = Month, %d = Day, %H = Hour, %M = Minute
formatted = now.strftime("%d-%m-%Y %H:%M")
print(formatted)  # e.g., "19-07-2026 18:15"
```

#### Parsing Strings into Dates (`strptime`)

To convert a date string back into a datetime object, use `.strptime()` (string parse time):

```python theme={null}
date_string = "2026-07-19"
parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(parsed_date)  # 2026-07-19 00:00:00
```

### 4. The `os` Module

The `os` module provides a way of interacting with your operating system, allowing you to manage files, folders, and file paths.

```python theme={null}
import os

# Working Directory
print(os.getcwd())              # Get Current Working Directory

# Listing files in the current directory
print(os.listdir("."))          

# Creating Directories
if not os.path.exists("temp_folder"):
    os.mkdir("temp_folder")

# Checking Paths
print(os.path.exists("temp_folder"))  # True

# Splitting and Joining Paths
full_path = os.path.join("temp_folder", "data.txt")
print(full_path)                # e.g., "temp_folder/data.txt" (on Mac/Linux)

# Extract directory name and filename
dir_name = os.path.dirname(full_path)
file_name = os.path.basename(full_path)
print(f"Dir: {dir_name}, File: {file_name}") # Dir: temp_folder, File: data.txt
```

<Tip>
  Always use `os.path.join()` instead of manually concatenating paths with string operations (like `"folder/" + "file.txt"`). This guarantees that your code will run correctly on Windows, macOS, and Linux without modification.
</Tip>

## 5. `string` Module

The **`string`** module provides useful predefined string constants that are commonly used for text processing, validation, and random string generation.

```python theme={null}
import string
```

| Constant                 | Description                    |
| ------------------------ | ------------------------------ |
| `string.ascii_lowercase` | Lowercase letters (`a-z`)      |
| `string.ascii_uppercase` | Uppercase letters (`A-Z`)      |
| `string.ascii_letters`   | All English letters (`a-zA-Z`) |
| `string.digits`          | Digits (`0-9`)                 |
| `string.hexdigits`       | Hexadecimal digits             |
| `string.octdigits`       | Octal digits (`0-7`)           |
| `string.punctuation`     | Special characters (`!@#$...`) |
| `string.whitespace`      | Space, tab, newline, etc.      |
| `string.printable`       | All printable ASCII characters |

### Example

```python theme={null}
import string

print(string.ascii_letters)
print(string.digits)
print(string.punctuation)
```

### Generate a Random Password

```python theme={null}
import random
import string

characters = (
    string.ascii_letters +
    string.digits +
    string.punctuation
)

password = "".join(random.choice(characters) for _ in range(12))
print(password)
```

***

## Import Methods Recap

Here are the different ways you can import built-in modules:

```python theme={null}
# Import entire module
import math
result = math.sqrt(16)

# Import specific functions
from math import sqrt, pi
result = sqrt(16)

# Import with alias (for convenience)
import datetime as dt
print(dt.date.today())

# Import everything (avoid this!)
from math import *
```

<Warning>
  Avoid `from module import *` as it can cause naming conflicts and makes code harder to understand.
</Warning>

***

## Practice & Exercises

To reinforce what you've learned in this section (import patterns, math constants, random selections, date manipulations, and operating system directories), practice with these interactive notebooks:

<CardGroup cols={2}>
  <Card title="Follow-Along Practice" icon="laptop-code">
    Practice importing specific functions, utilizing ceil/floor and trigonometry functions, generating random bounds, executing date arithmetic, formatting/parsing datetimes, and building file system paths.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/python%20material/python4ai/public/notebooks/basics_exercises/Builtin_Modules_Practice.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/python4ai/blob/master/public/notebooks/basics_exercises/Builtin_Modules_Practice.ipynb) | <a href="/public/notebooks/basics_exercises/Builtin_Modules_Practice.ipynb" download>📥 Download</a>
  </Card>

  <Card title="Practice Exercises" icon="pen-to-square">
    Test your knowledge with hands-on exercises on calculating cosine of 60 degrees, picking random leaders and unique helpers, calculating days left in the year, and building directories with joined output logs.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/python%20material/python4ai/public/notebooks/basics_exercises/Builtin_Modules_Exercises.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/python4ai/blob/master/public/notebooks/basics_exercises/Builtin_Modules_Exercises.ipynb) | <a href="/public/notebooks/basics_exercises/Builtin_Modules_Exercises.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>

## What's next?

Now that you know how to use Python's built-in modules, let's learn how to read, write, and process text, JSON, and CSV data formats using only Python's built-in tools.

<Card title="Working with Data" icon="arrow-right" href="/libraries-apis/working-with-data">
  Learn to process text, JSON, and CSV data files
</Card>
