> ## 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.

# Import packages

> Use Python packages and libraries

## Using packages

Python packages add new functionality to your programs. There are two types:

* **Built-in**: Come with Python (no installation needed)
* **External**: Need to install first with pip

## Understanding the terminology

Let's clarify what these terms mean:

* **Module**: A single Python file (like `math.py`)
* **Package**: A folder containing multiple modules
* **Function**: A reusable block of code (like `print()` or `sqrt()`)
* **Class**: A 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 with multiple toolboxes
* A **function** is like a specific tool (hammer, screwdriver)
* A **class** is like a blueprint for building tools

## Import patterns explained

```python theme={null}
# Pattern 1: Import the whole module
import math
# Now use: math.sqrt(16)

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

What's happening:

* `import math` - brings in the entire math toolbox
* `from math import sqrt` - takes just the sqrt tool from the math toolbox

## Built-in modules

Python includes many useful modules:

```python theme={null}
# Import entire module
import random

# Use module functions
number = random.randint(1, 10)
choice = random.choice(["apple", "banana", "orange"])
```

### Common built-in modules

```python theme={null}
# Date and time
import datetime
today = datetime.date.today()
print(today)  # 2024-01-15

# Operating system
import os
current_dir = os.getcwd()
print(current_dir)

# JSON data
import json
data = {"name": "Alice", "age": 30}
json_string = json.dumps(data)
```

## Import methods

Different ways to import:

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

# Import specific functions
from math import sqrt, pi
result = sqrt(16)
circle_area = pi * radius ** 2

# Import with alias
import pandas as pd
df = pd.DataFrame(data)

# 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>

## Installing packages

External packages need installation:

```bash theme={null}
# Install a package
pip install requests

# Install specific version
pip install requests==2.28.0

# Install multiple packages
pip install pandas numpy matplotlib
```

<Tip>
  Always ensure your virtual environment is activated before installing! This is the #1 source of import errors. If you get "ModuleNotFoundError" after installing, you probably installed to the wrong environment. [Learn more about virtual environments](/getting-started/virtual-environments).
</Tip>

## Sharing your project: requirements.txt

When you share your Python project, others need to know which packages to install. The standard way is using a `requirements.txt` file:

### Creating requirements.txt

List all your project's packages:

```bash theme={null}
pip freeze > requirements.txt
```

This creates a file like:

```
certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.2.0
```

### Installing from requirements.txt

When someone gets your project, they run:

```bash theme={null}
pip install -r requirements.txt
```

This installs all the packages at once!

<Note>
  Later in the course, we'll learn about `uv` - a modern, faster alternative to pip that makes package management even easier.
</Note>

## Using external packages

After installation, import and use:

```python theme={null}
# Web requests
import requests

response = requests.get("https://api.example.com/data")
data = response.json()

# Data analysis
import pandas as pd

# Create a simple DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35],
    'city': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
```

<Note>
  Always use virtual environments for projects. They prevent package conflicts between different projects.
</Note>

## Finding packages

Where to find packages:

* [PyPI](https://pypi.org) - Official Python package index
* [Awesome Python](https://github.com/vinta/awesome-python) - Curated list
* **ChatGPT** - Ask "What Python package should I use for \[task]?" - Great for recommendations and comparisons
* Google "Python package for \[task]"

<Tip>
  ChatGPT is excellent for finding packages. Try asking: "What's the best Python package for reading Excel files?" or "Compare pandas vs polars for data analysis." It can explain which package to use and why.
</Tip>

## Common mistakes

<AccordionGroup>
  <Accordion title="Import errors">
    ```python theme={null}
    # Wrong - package not installed or venv not activated
    import pandas  # ModuleNotFoundError

    # Right - install first
    # Run: pip install pandas
    import pandas
    ```
  </Accordion>

  <Accordion title="Name conflicts">
    ```python theme={null}
    # Wrong - overwrites built-in
    import datetime
    datetime = "2024-01-01"  # Now module is gone!

    # Right - use different names
    import datetime
    date_string = "2024-01-01"
    ```
  </Accordion>
</AccordionGroup>

## What's next?

Learn to connect to APIs and fetch data from the internet!

<Card title="Working with APIs" icon="arrow-right" href="/libraries-apis/working-with-apis">
  Connect to online services
</Card>
