Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults

AI code is a fast first draft, and you sign it. One cart-total script with three planted faults: a method that does not exist, a crash on an empty cart, and > where the requirement meant >=. Each is found by a different step.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Apply the six-step habit: read, run, edge cases, requirements, ask why, commit
  • Find a method that does not exist by running the code
  • Catch a crash with an edge case like an empty cart
  • Spot an off-by-one comparison by checking output against the requirements

Before you start

  • Python Conditionals and Loops
  • Run a Python File and Read the Error
  • Prompting Fundamentals for Code

Think about a friend who writes a letter for you and finishes it in a minute. It's neat, it reads well, and most of it is right. That's a big help. But you read it before you sign, and you spot a wrong date, because you know what it should say. You fix that, and only then does your name go at the bottom.

Code from an AI tool works the same way. It isn't good and it isn't bad. It's a fast first draft, and you're the one who signs it.

The habit: six steps, in order

Six steps in order: read, run, edge cases, requirements, ask why, commit; if a step finds a problem, fix it and go back to the start 1 Read 2 Run 3 Edge cases 4 Requirements 5 Ask why 6 Commit found a problem? fix it and start again, because a fix can break something else
Each step catches something the others miss.
  1. Read it, and say each line in your own words.
  2. Run it, and see what it does.
  3. Try edge cases, the odd inputs nobody mentioned.
  4. Check it against the requirements, what you asked for.
  5. Ask why about anything you can't explain.
  6. Only then, commit.

A small job

Here's what we want: add up the prices in a cart, give ten percent off when the total is 100 or more, and print the total and the average price. Here's an example of code an AI tool might return. It's short and looks tidy, but three faults are hiding in it.

# An example of code an AI tool might return
cart = [40.0, 35.5, 24.5]

total = 0
for price in cart:
    total = total + price

average = total / len(cart)

if total > 100:
    total = total * 0.9

total = total.round(2)

print(f"Total: {total:.2f}")
print(f"Average: {average:.2f}")

Step 1: read it

Don't run anything yet. The cart has three prices. The loop takes the total to 40, then 75.5, then 100. The average is the total divided by how many prices there are. If the total is more than 100, we keep 90 percent of it.

Then there's total.round(2), and you can't explain that one, because you haven't seen it anywhere. Don't guess. Put a question mark beside it. If you can't say what a line does, that line isn't checked yet.

Step 2: run it

Traceback (most recent call last):
  File "S01L09_1_CheckingAICode\ai_draft.py", line 13, in <module>
    total = total.round(2)
            ^^^^^^^^^^^
AttributeError: 'float' object has no attribute 'round'

Last line first: a float has no round method, and it points at line 13, our question mark. The code calls a method that doesn't exist. It looks right, and that's exactly why you run it. That's fault one. You don't need the line at all, because :.2f in the print already shows two decimals, so delete it.

Total: 100.00
Average: 33.33

No traceback now, so it's tempting to stop and commit. But a program that runs can still be wrong. All you know is that it finished, for this one cart.

Step 3: edge cases

An edge case is an input at the limit, the kind that's easy to forget. What if the cart is empty? What if there's only one price? What if the total lands exactly on a limit? Look at your inputs and ask: what's the smallest, the emptiest, and what sits right on the line?

Change only the first line to cart = []:

Traceback (most recent call last):
  File "S01L09_1_CheckingAICode\empty_cart.py", line 7, in <module>
    average = total / len(cart)
              ~~~~~~^~~~~~~~~~~
ZeroDivisionError: division by zero

The loop adds nothing, the length is 0, so it's 0 divided by 0. It's the same crash as the average() example in Thinking like a Python architect. That's fault two. The requirements didn't mention an empty cart, so the behaviour is your decision. Here, we'll print "Cart is empty".

Step 4: check the requirements

Put what you asked for beside what you got. Adding up: 40 + 35.5 + 24.5 is 100, right. Total and average printed: both there. Ten percent off at 100 or more: the total is exactly 100, so it should print 90.00. It printed 100.00. No error, just a wrong answer.

Why? The code says total > 100, and 100 isn't greater than 100. You even read past it in step one. Change it to >= and 100 moves inside. Fault three: one small character, and the requirements showed it.

Step 5: ask why

Pick a line you'd like explained and ask the tool, for example: "Why is the average worked out before the discount?" The order matters. The average line sits above the if, so it uses the full prices. You asked for the average price of the items, so that's what you want; if you'd wanted something else, this is where you'd catch it.

A clear answer still isn't proof, so check what the tool tells you against the code. If you can't follow it, ask again in simpler words. You should be able to explain every line yourself before you keep it.

The fixed version

carts = [
    [30.0, 20.0],
    [40.0, 35.5, 24.5],
    [],
]

for cart in carts:
    if len(cart) == 0:
        print("Cart is empty")
        continue

    total = 0
    for price in cart:
        total = total + price

    average = total / len(cart)

    if total >= 100:
        total = total * 0.9

    print(f"Total: {total:.2f}")
    print(f"Average: {average:.2f}")
Total: 50.00
Average: 25.00
Total: 90.00
Average: 33.33
Cart is empty

Three carts, so one run covers every case. 50 is under the limit, so no discount. The second cart reaches 100 and now gets it: 90.00. The empty cart prints a message instead of crashing. Three faults, each found by a different step: the run, the edge case and the requirements.

Step 6: commit

Every check has passed, so run down the list once more, then save this version with Git and a short message that says what it does (see Git and GitHub fundamentals). If something breaks later, you can come back to this point. And remember the letter: your name is on this now, whoever wrote the first draft.

Keep it as a checklist

You can keep the habit right beside the code as comments:

# Paste the program your AI tool wrote below.

names = ["Asha", "Ben", "Chen"]
for name in names:
    print(f"Hello, {name}!")

# 1 Read it: what does each line do?
#   Each name gets one greeting line.
# 2 Run it: does it finish without an error?
#   Yes, three lines print.
# 3 Edge case I tried: an empty list.
#   Nothing prints, and nothing crashes.
# 4 The requirements say: greet every name.
#   It does.
# 5 Question I asked the tool: why a for loop?
#   One line of code covers any number of names.
# 6 Commit when every check passes.
Hello, Asha!
Hello, Ben!
Hello, Chen!

Quick recap

StepFound here
Reada line you couldn't explain: total.round(2)
RunAttributeError: that method doesn't exist
Edge casesZeroDivisionError on an empty cart
Requirements> where "100 or more" meant >=
Ask whyconfirms the average uses the full prices
Commitonly after all of the above

Try it yourself

Ask an AI tool for a small program, then find one case it missed.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 10 of 48

Previous
Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
Next post
Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python for AI: The Five Tools You Actually Need

The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.

Thinking Like a Python Architect in an AI-First World

Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.

Your First Python Program: print, Comments, sep and end

Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.

Set Up PyCharm for Python: Install, First Project and First Run

Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.

On this page

  • The habit: six steps, in order
  • A small job
  • Step 1: read it
  • Step 2: run it
  • Step 3: edge cases
  • Step 4: check the requirements
  • Step 5: ask why
  • The fixed version
  • Step 6: commit
  • Keep it as a checklist
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.