# How to write and fix code with AI

> Write a small script, fix a spreadsheet formula or understand code someone sent you. Pick the task and the language, and get working code with notes.

Source: https://www.try.chatmodel.ai/tools/code-assistant · tool · updated 2026-09-28 · by the chatmodel team, tested in the app (https://www.chatmodel.ai)

A script to rename your holiday photos, a spreadsheet formula that won't work, a snippet from a forum you don't understand. Describe what you need or paste the code, pick the task, and Code Assistant does the rest.

## How it works

1. In the Input box, describe what you need or paste your code.
2. Pick a Task (for example Write Code or Debug) and a Language (for example Python).
3. Press Run and read the code and the notes in the Output tab.

## What it's good for

- **Tidy up files on your computer**: A short Python script to rename or sort hundreds of photos by date.
- **Fix a spreadsheet formula**: Paste the formula that gives an error and get a corrected one, with the reason it failed.
- **Understand code someone sent you**: Get a plain explanation of what a snippet does before you run it.
- **Small website changes**: A bit of HTML or JavaScript for a club or small business website.
- **Move code to another language**: Turn a script from one language into another with Convert.
- **A second pair of eyes**: Ask for a Code Review to spot risky or messy parts of a script.

## Examples

### A script to rename photos

**What goes in (Task: Write Code, Language: Python):**

> I have a folder on my laptop called "Italy 2025" with about 400 photos from my phone. They all have names like IMG_4821.JPG. I'd like a small Python script that renames every photo in the folder using the date it was taken, like 2025-06-14_001.jpg, 2025-06-14_002.jpg, and so on, so they sort in order. Please don't delete anything, and tell me how to run it on a Mac. I've never run a script before.

**What comes back:**

> # Photo Renaming Script
>
> This script renames JPEG images in a specified directory based on their EXIF creation date, ensuring chronological sorting.
>
> ## Features
>
> *   **EXIF Date Extraction**: Reads the EXIF data of JPEG files to determine the original capture date and time.
> *   **Chronological Renaming**: Renames files in the format `YYYY-MM-DD_NNN.jpg`, where `NNN` is a sequential counter for each day.
> *   **Error Handling**: Gracefully handles files without EXIF data or files that are not JPEGs.
> *   **Safety First**: Does not delete original files; renames them in place.
>
> ## Prerequisites
>
> *   **Python 3**: Ensure you have Python 3 installed on your Mac. You can check this by opening the Terminal and typing `python3 --version`. If not installed, download it from [python.org](https://www.python.org/).
> *   **Pillow Library**: This script uses the Pillow library to read EXIF data. Install it using pip:
>     ```bash
>     pip3 install Pillow
>     ```
>
> ## Python Script
>
> ```python
> import os
> import sys
> from datetime import datetime
> from PIL import Image
> from PIL.ExifTags import TAGS
>
> def get_creation_date(filepath):
>     """
>     Retrieves the creation date from a JPEG file's EXIF data.
>
>     Args:
>         filepath (str): The full path to the image file.
>
>     Returns:
>         datetime or None: A datetime object representing the creation date,
>                           or None if EXIF data is not found or unreadable.
>     """
>     try:
>         image = Image.open(filepath)
>         exif_data = image._getexif()
>
>         if exif_data is None:
>             return None
>
>         # Common EXIF tags for date/time original
>         # 36867 is DateTimeOriginal
>         # 306 is DateTime
>         date_tag = None
>         for tag_id, value in exif_data.items():
>             tag_name = TAGS.get(tag_id, tag_id)
>             if tag_name in ('DateTimeOriginal', 'DateTime'):
>                 date_tag = value
>                 break
>
>         if date_tag:
>             # EXIF date format is usually 'YYYY:MM:DD HH:MM:SS'
>             return datetime.strptime(date_tag, '%Y:%m:%d %H:%M:%S')
>     except IOError:
>         print(f"Warning: Could not open or read EXIF data for {filepath}. Skipping.")
>         return None
>     except Exception as e:
>         print(f"Warning: An unexpected error occurred while processing EXIF for {filepath}: {e}. Skipping.")
>         return None
>     return None
>
> def rename_photos_in_directory(directory_path):
>     """
>     Renames all JPEG photos in a given directory based on their creation date.
>
>     Args:
>         directory_path (str): The path to the directory containing the photos.
>     """
>     if not os.path.isdir(directory_path):
>         print(f"Error: Directory '{directory_path}' not found.")
>         return
>
>     files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]
>     # Filter for JPEG files and ensure case-insensitivity for extensions
>     jpeg_files = sorted([f for f in files if f.lower().endswith(('.jpg', '.jpeg'))])
>
>     if not jpeg_files:
>         print(f"No JPEG files found in '{directory_path}'.")
>         return
>
>     date_counts = {}  # To keep track of sequence numbers per day
>     renamed_count = 0
>
>     print(f"Processing photos in: {directory_path}")
>
>     for filename in jpeg_files:
>         original_filepath = os.path.join(directory_path, filename)
>         creation_date = get_creation_date(original_filepath)
>
>         if creation_date:
>             date_str = creation_date.strftime('%Y-%m-%d')
>
>             # Increment counter for this date
>             if date_str not in date_counts:
>                 date_counts[date_str] = 0
>             date_counts[date_str] += 1
>             sequence_num = date_counts[date_str]
>
>             # Format the new filename: YYYY-MM-DD_NNN.jpg
>             new_filename = f"{date_str}_{sequence_num:03d}.jpg"
>             new_filepath = os.path.join(directory_path, new_filename)
>
>             # Avoid renaming if the file is already named correctly or if the new name conflicts
>             if filename == new_filename:
>                 print(f"Skipping already correctly named file: {filename}")
>                 continue
>             if os.path.exists(new_filepath):
>                 print(f"Warning: Target file '{new_filename}' already exists. Skipping rename for '{filename}'.")
>                 continue
>
>             try:
>                 os.rename(original_filepath, new_filepath)
>                 print(f"Renamed '{filename}' to '{new_filename}'")
>                 renamed_count += 1
>             except OSError as e:
>                 print(f"Error renaming '{filename}' to '{new_filename}': {e}")
>         else:
>             print(f"Skipping '{filename}': Could not determine creation date from EXIF.")
>
>     print(f"\nFinished processing. {renamed_count} photos renamed.")
>
> if __name__ == "__main__":
>     # IMPORTANT: Replace this with the actual path to your "Italy 2025" folder.
>     # For example: "/Users/yourusername/Pictures/Italy 2025"
>     # You can drag and drop the folder onto the Terminal window to get its path.
>
>     # Example using command-line argument:
>     if len(sys.argv) > 1:
>         folder_to_process = sys.argv[1]
>     else:
>         # If no argument is provided, prompt the user or use a default (use with caution)
>         # folder_to_process = input("Enter the full path to the photo folder: ")
>         # For safety, if no argument is given, it's better to exit and ask for it.
>         print("Usage: python rename_photos.py <path_to_your_photo_folder>")
>         print("Example: python rename_photos.py /Users/yourusername/Pictures/Italy 2025")
>         sys.exit(1)
>
>     rename_photos_in_directory(folder_to_process)
> ```
>
> ## How to Run the Script on a Mac
>
> 1.  **Save the Script**:
>     *   Open a plain text editor (like TextEdit, VS Code, Sublime Text, etc.).
>     *   Copy the Python code above and paste it into the editor.
>     *   Save the file with a `.py` extension, for example, `rename_photos.py`. Save it in a place you can easily find, like your `Documents` folder.
>
> 2.  **Open Terminal**:
>     *   Go to your Applications folder, then Utilities, and open `Terminal`.
>
> 3.  **Navigate to the Script's Directory**:
>     *   In the Terminal, type `cd ` (note the space after `cd`).
>     *   Drag and drop the folder where you saved `rename_photos.py` onto the Terminal window. This will automatically fill in the path.
>     *   Press Enter.
>     *   Example: `cd /Users/yourusername/Documents`
>
> 4.  **Run the Script**:
>     *   To run the script, you need to provide the path to your "Italy 2025" folder as an argument.
>     *   Type the following command, replacing `/path/to/your/Italy 2025` with the actual path to your folder:
>         ```bash
>         python3 rename_photos.py /path/to/your/Italy 2025
>         ```
>     *   **Tip**: You can get the path to your "Italy 2025" folder by opening Finder, navigating to the folder, and then dragging and dropping the "Italy 2025" folder itself onto the Terminal window *after* you've typed `python3 rename_photos.py ` (with the space).
>
>     *   **Example**: If your photos are in your `Pictures` folder, your command might look like this:
>         ```bash
>         python3 rename_photos.py /Users/yourusername/Pictures/Italy\ 2025
>         ```
>         *(Note the backslash `\` before the space in "Italy 2025" if you're typing the path manually. Dragging and dropping usually handles this automatically.)*
>
> 5.  **Review the Output**:
>     *   The script will print messages indicating which files are being renamed or if any issues are encountered.
>     *   Once it finishes, check your "Italy 2025" folder to confirm the renaming.
>
> ## Important Notes
>
> *   **Backup First**: Although the script is designed not to delete files, it's always a good practice to back up your photos before running any renaming script.
> *   **EXIF Data**: The script relies on the EXIF data embedded in your photos. If your photos have had their EXIF data stripped or modified, the script might not be able to determine the original date. In such cases, those files will be skipped and a warning will be printed.
> *   **Case Sensitivity**: The script handles file extensions in a case-insensitive manner (`.JPG`, `.jpg`, `.jpeg`, `.JPEG`).
> *   **File Conflicts**: If a file with the target name already exists (e.g., after a previous run or if you have manually created files), the script will skip renaming the current file to avoid overwriting.
> *   **Permissions**: Ensure your user account has permission to rename files in the target directory.

### A spreadsheet formula that fails

**What goes in (Task: Debug):**

> I keep a household budget in Google Sheets. Column A has the date, column B the category (like Groceries or Fuel) and column C the amount. I want a cell that adds up everything spent on Groceries in March 2026. I wrote this formula but it shows an error:
>
> =SUMIFS(C:C, B:B, Groceries, A:A, ">=1/3/2026", A:A, "<=31/3/2026")
>
> What's wrong with it, and what should it be?

**What comes back:**

> # Debugging `SUMIFS` Formula for Household Budget
>
> The provided `SUMIFS` formula contains several issues that prevent it from correctly calculating the total spent on "Groceries" in March 2026.
>
> ## Root Cause Analysis
>
> 1.  **Category String Literal:** The `Groceries` criterion in `SUMIFS(C:C, B:B, Groceries, ...)` is treated as a cell reference rather than a text string. Without quotes, Google Sheets interprets `Groceries` as a cell containing the value to match, which is likely not intended.
> 2.  **Date Format Ambiguity:** The date criteria `">=1/3/2026"` and `"<31/3/2026"` use a `day/month/year` format. While Google Sheets *can* sometimes interpret this, it's highly dependent on regional settings and can lead to unexpected behavior or errors if the settings don't match. The standard and most robust way to specify dates in formulas is using the `DATE` function or a consistent `year-month-day` format.
> 3.  **Inclusive End Date:** The end date criterion `"<31/3/2026"` is inclusive for the day. However, when comparing dates, it's often safer and more common to use `<` with the *start* of the *next* period to ensure all values within the target month are captured, especially if times are involved (though less critical in this specific sheet context, it's good practice).
>
> ## Corrected Formula
>
> The corrected formula addresses these issues by:
>
> *   Enclosing the category name in double quotes.
> *   Using the `DATE` function for unambiguous date comparisons, ensuring correct handling of the month and year regardless of regional settings.
> *   Using `<` with the first day of the *next* month to ensure all days of March are included.
>
> ```excel
> =SUMIFS(C:C, B:B, "Groceries", A:A, ">=2026-03-01", A:A, "<2026-04-01")
> ```
>
> Alternatively, using the `DATE` function for maximum clarity and robustness:
>
> ```excel
> =SUMIFS(C:C, B:B, "Groceries", A:A, ">="&DATE(2026, 3, 1), A:A, "<"&DATE(2026, 4, 1))
> ```
>
> ### Explanation of Corrections
>
> *   `"Groceries"`: The category name is now correctly enclosed in double quotes, treating it as a literal string.
> *   `">=2026-03-01"` and `"<2026-04-01"`: These use the unambiguous `YYYY-MM-DD` format, which Google Sheets reliably interprets as dates. The first condition includes all dates on or after March 1, 2026. The second condition includes all dates strictly *before* April 1, 2026, effectively capturing all of March.
> *   `">="&DATE(2026, 3, 1)` and `"<"&DATE(2026, 4, 1)`: This approach uses the `DATE(year, month, day)` function to construct the dates programmatically. This is the most robust method as it completely bypasses any regional settings interpretation for dates. The `&` operator concatenates the comparison operator (`>=` or `<`) with the date value.

### A small script that adds wrong

**What goes in (Task: Debug, Language: Python):**

> This little script is supposed to add up my monthly expenses from a list, but it always prints a strange number instead of the total. What's wrong?
>
> expenses = ["45.20", "12.99", "80.00", "7.50"]
> total = 0
> for e in expenses:
>     total = total + e
> print("Total spent:", total)

**What comes back:**

> # Debugging Report: Expense Calculator
>
> ## Root Cause Analysis
>
> The script fails because it attempts to add strings to a numeric type (`int` or `float`). The `expenses` list contains expense values as strings (e.g., `"45.20"`). When the loop iterates, it tries to perform string concatenation (`0 + "45.20"`) which results in a string `"45.20"`. In subsequent iterations, it continues concatenating strings, leading to an unexpected string output rather than a numerical sum.
>
> ## Corrected Code
>
> ```python
> expenses = ["45.20", "12.99", "80.00", "7.50"]
> total = 0.0  # Initialize total as a float to handle decimal values
> for e in expenses:
>     try:
>         # Convert each expense string to a float before adding
>         total += float(e)
>     except ValueError:
>         # Handle cases where an item in the expenses list is not a valid number
>         print(f"Warning: Skipping invalid expense entry: {e}")
>
> print(f"Total spent: {total:.2f}")
> ```
>
> ## Explanation of Fixes
>
> 1.  **Type Conversion**: The core issue was the type mismatch. Each string element `e` from the `expenses` list is now explicitly converted to a `float` using `float(e)` before being added to the `total`.
> 2.  **Initialization**: The `total` variable is initialized to `0.0` (a float) instead of `0` (an integer). This ensures that the `total` variable is of a type that can accommodate decimal values from the start, preventing potential precision loss if intermediate calculations were to occur without it.
> 3.  **Error Handling**: A `try-except` block is added to gracefully handle `ValueError`. This occurs if any item in the `expenses` list cannot be converted to a float (e.g., if it were accidentally `None` or contained non-numeric characters). This makes the script more robust.
> 4.  **Formatted Output**: The final `print` statement uses an f-string with `:.2f` formatting to display the total spending rounded to two decimal places, which is standard for currency.

## Tips

- Say what you're working with: Excel or Google Sheets, Windows or Mac, and which folder or file.
- Paste the exact error message if there is one. It's often the fastest clue.
- Ask how to run it. If you've never run a script, say so and it will explain.
- Try code on a copy of your files first, never on the only copy of your photos.
- Pick the Language that matches what you'll use. If you're not sure, describe the task and let it choose.

## What Code Assistant does

Code Assistant is like having an experienced programmer next to you. You describe what you need, or paste some code, and it gives you clean code with short notes on the tricky parts.

Code always comes in a separate box, so it's easy to copy. It's written to be tidy and modern, to check for things that could go wrong, and never to include passwords or private keys.

You don't need to be a programmer. Most people use it for small, practical jobs: a formula, a script to sort files, a change to a web page.

## What you can change

**Task**

- **Write Code**: new code from your description.
- **Explain Code**: what a piece of code does, step by step.
- **Debug**: finds the mistake, fixes it and explains why it went wrong.
- **Optimize**: makes code faster or easier to read, and says what it traded off.
- **Convert**: rewrites code in another language, the way that language is usually written.
- **Code Review**: points out risky or messy parts and suggests improvements.

**Language**: JavaScript, TypeScript, Python, Java, C#, C++, Go, Rust, PHP, Ruby, Swift or Kotlin.

## What it won't do

- It won't run the code for you or touch your files. You copy it and run it yourself.
- It can't see your computer, so it guesses details you don't give it, like folder names.
- It can make mistakes. Test on a copy first, and don't run code you don't understand on important files.

Just want to understand a topic, not code it? Try [Learn](https://www.try.chatmodel.ai/tools/learn). Building a budget? The [household budget guide](https://www.try.chatmodel.ai/guides/household-budget) or [Create a Spreadsheet](https://www.try.chatmodel.ai/tools/create-spreadsheet) may be quicker. See all the [tools](https://www.try.chatmodel.ai/tools).

[Open Code Assistant in chatmodel](https://www.chatmodel.ai/tools/code-assistant?prompt=Write+a+Python+script+that+renames+all+the+photos+in+a+folder+using+the+date+they+were+taken%2C+like+2024-07-15_001.jpg.)

## Frequently asked questions

### Do I need to know how to code?

No. You can describe what you want in plain words. Say you're a beginner and ask it to explain how to use the result.

### What tasks can I pick?

Write Code, Explain Code, Debug, Optimize, Convert and Code Review.

### Which languages does it support?

The Language menu has JavaScript, TypeScript, Python, Java, C#, C++, Go, Rust, PHP, Ruby, Swift and Kotlin.

### Can it help with Excel or Google Sheets formulas?

Yes. Paste the formula, describe your columns and pick Debug. Spreadsheet formulas aren't in the Language menu, so just describe which app you use.

### Is the code safe to run?

It's written to check its inputs and avoid risky shortcuts, but always read the notes and test on a copy of your files first.
