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

# Organizing Python Code into Reusable Functions

> Learn how to split a growing Python script into separate helper files and import functions across modules to keep your code clean.

As soon as a Python script grows beyond a couple of dozen lines, it starts to become difficult to read and maintain. The standard solution is to extract distinct pieces of logic into well-named functions, and then move those functions into separate files when they could be useful elsewhere. This approach makes each part of your codebase easier to understand in isolation, easier to test, and easy to reuse across multiple scripts. It's the same pattern used in every serious Python project.

## Creating helper functions

Let's add reusable helper functions to your `sales-analysis` project. In the `sales-analysis/` folder, create a new file called `helpers.py`:

```python theme={null}
# helpers.py

def calculate_total(quantity, price):
    """Calculate the line total for a single sales item."""
    return quantity * price

def format_currency(amount):
    """Format a numeric amount as a dollar string."""
    return f"${amount:,.2f}"
```

Two focused functions, each doing exactly one thing. Notice the docstrings — they make it clear what the function does without needing to read the implementation.

<Tip>
  The `:.2f` format specifier rounds a floating-point number to two decimal places. The `,` adds thousands separators. Together they produce clean currency output like `$1,999.98`.
</Tip>

## Using your functions in the main script

Update `analyzer.py` in the same folder to import and use your new helpers:

```python theme={null}
# analyzer.py
import pandas as pd
from helpers import calculate_total, format_currency

# Read the sales data
df = pd.read_csv("data/sales.csv")

# Calculate the total for each row
totals = []
for index, row in df.iterrows():
    total = calculate_total(row["quantity"], row["price"])
    totals.append(total)

# Add the calculated totals as a new column
df["total"] = totals

# Display each product with its formatted total
print("Sales Data:")
for index, row in df.iterrows():
    formatted = format_currency(row["total"])
    print(f"  {row['product']}: {formatted}")

# Print the grand total
grand_total = df["total"].sum()
print(f"\nGrand Total: {format_currency(grand_total)}")
```

## How imports work

When you write `from helpers import calculate_total`:

1. Python looks for `helpers.py` in the same folder as `analyzer.py`
2. It runs `helpers.py` and makes the functions available in your current scope
3. You can call `calculate_total()` directly, as if you'd defined it in the same file

<Note>
  This simple import works because both files are in the same directory. If your helper was in a subfolder, you'd use the dotted import syntax covered in the Python paths page.
</Note>

## What you've accomplished

Take a moment to appreciate how far you've come. Starting from a single Python file, you now have:

* An organized project with separate folders for code, data, and output
* A clear understanding of how Python locates files and modules
* A script that reads real CSV data and produces formatted results
* Reusable helper functions in a dedicated module

This is how real Python projects are structured. These same patterns appear in data science pipelines, web applications, and AI projects.

## What's next?

Now that you can structure and organize local Python projects, let's build a complete end-to-end weather data analysis project using a real API.

<Card title="Weather data analysis project" icon="arrow-right" href="/weather-project/weather-data-analysis-project">
  Build a weather analysis project with APIs and visualization
</Card>
