Ravindra BagaleCourses & study guides Track your progress

Learn Python with ChatGPT: Write, Run and Fix Your First Programs

Generative AI course · Chapter 34 · Estimated reading time: 13 minutes

Many people start learning Python, get one red error message, and give up. The error looks scary, nobody is around to explain it, and searching online gives answers for a different problem. An AI chat tool changes this. It can explain every line in simple words, show you what an error means and suggest a fix, at any time of day. But there is a trap: if AI writes everything and you only copy, you learn nothing. In this chapter you will use ChatGPT (or any AI chat tool) as a tutor, not a ghost-writer: you will write a bill calculator, clean a messy CSV file, and fix a real error message yourself.

What you will learn in this chapter

  • Where to run Python for free, in a browser or on your laptop
  • The tutor prompt: make AI teach instead of doing the work for you
  • Write and run a bill calculator
  • Clean a messy CSV file with pandas
  • Read a traceback and fix it with AI's help
  • A 4-step habit for learning from every error
  • What AI gets wrong when it teaches Python

1. Suppose Rahul wants to automate his shop bills

Suppose Rahul runs a small stationery shop. Every evening he adds up bills on a calculator and makes mistakes when he is tired. He has heard that "Python can do this", but he has never written a program.

He opens ChatGPT and types: "Write a Python program for my shop bills." He gets 60 lines of code, copies them, and something goes wrong. He does not know which line, or why.

Now suppose he types this instead: "I am learning Python from zero. Teach me to write a small bill calculator, one small step at a time. After each step, ask me to run it and tell you the output." Now he writes 10 lines he understands, runs them, and knows what each line does.

The tool is the same. The prompt decides whether you learn.

2. Where to run your Python

You need a place to run code. Two free choices:

Option Good for How to start
Google Colab Starting today, nothing to install Go to colab.research.google.com, sign in with a Google account, click New notebook, type code in a cell and press the play button
Python on your laptop Working with your own files, offline Install Python 3 and a code editor

Colab runs in your browser and is free to start with a Google account. It also has Gemini built in for eligible users: after an error, look for a button that offers to explain the error.

Related guide

To install Python on your own laptop, with a virtual environment and Jupyter, follow the step-by-step setup in Install Python 3, a venv and Jupyter for Data Science. This chapter does not repeat the setup; it shows how to learn Python with an AI tutor once Python is running.

3. The tutor prompt

Save this prompt and start every learning chat with it:

You are my patient Python tutor. I am a complete beginner.
Rules:
1. Teach one small idea at a time, with a tiny example.
2. Do not give me the full solution unless I ask "show solution".
3. When I share an error, explain what it means in simple words,
   point to the exact line, and give me a hint first, not the fix.
4. After each step, ask me to run the code and tell you what happened.
5. Use simple English and short sentences.
Today I want to build: [your small project].
Learning with an AI tutor: one small step at a time Steps from top to bottom: 1 Ask for one step, Use the tutor prompt; 2 Predict, Say what each line will do; 3 Run it, In Colab or on your laptop; 4 Read any error, Last line first, then your line; 5 Ask for a hint, Fix it yourself, then ask why. 1Ask for one stepUse the tutor prompt 2PredictSay what each line will do 3Run itIn Colab or on your laptop 4Read any errorLast line first, then your line 5Ask for a hintFix it yourself, then ask why

Learning with an AI tutor: one small step at a time

Ravindra Bagale's Tip

The mistake is pasting AI's code and running it without reading it. When it works, you learn nothing; when it breaks, you are stuck. The fix is simple: before you run any line AI gives you, say in your own words what you think it will do. Then run it and compare. If you were wrong, ask AI "why?". That one habit turns copying into learning.

4. Worked example 1: a bill calculator

The prompt (after the tutor prompt):

Today I want to build: a bill calculator for my stationery shop.
Items have a name, quantity and price. Then there is a 5% festival discount.
Show me step 1 only.

Expected output (yours will be similar, not the same): AI shows a list of items, explains that a list holds many values, and asks you to print it. Over a few steps, you build something like this:

# Shop bill calculator: items, quantity, price, a 5% festival discount, total.
items = [("Notebook", 4, 40), ("Pen pack", 2, 55), ("Geometry box", 1, 120)]
DISCOUNT = 0.05
subtotal = 0
for name, qty, price in items:
    line = qty * price
    subtotal += line
    print(f"{name:<13} {qty} x {price:>4} = {line:>7.2f}")
discount = subtotal * DISCOUNT
print(f"{'Subtotal':<22} {subtotal:>8.2f}")
print(f"{'Discount 5%':<22} {-discount:>8.2f}")
print(f"{'Total to pay':<22} {subtotal - discount:>8.2f}")

Real output (we ran this on 19 October 2026):

Notebook      4 x   40 =  160.00
Pen pack      2 x   55 =  110.00
Geometry box  1 x  120 =  120.00
Subtotal                 390.00
Discount 5%              -19.50
Total to pay             370.50

Check it yourself. 160 + 110 + 120 = 390. 5% of 390 is 19.50. 390 minus 19.50 is 370.50. Always check the first result of any program by hand, even a tiny one.

Learning questions to ask AI next:

  • "What does :<13 mean inside the f-string?"
  • "Why did you write DISCOUNT in capital letters?"
  • "How would I ask the user to type the items instead?"

5. Worked example 2: clean a messy CSV file

Suppose a teacher shares a student list exported from a form. It has extra spaces, mixed capital letters, a repeated student, a missing mark and the word "abc" where a number should be:

name,city,marks
 Priya Kulkarni ,pune,78
Amit Shinde,Pune,
priya kulkarni,PUNE,78
Rahul Patil , nashik ,abc
Neha Joshi,Nagpur,91

The prompt:

I have a file students.csv with columns name, city, marks. Problems: extra spaces,
mixed capital letters, one repeated student, empty marks, and text instead of marks.
Using pandas, show me code that cleans it step by step, with a comment on every line.
Do not delete bad rows silently: print them first so I can see what was removed.

Expected output (yours will be similar, not the same): code like the one below. We ran it on the file above:

import pandas as pd
df = pd.read_csv("students.csv")
print("Before:", len(df), "rows")
df["name"] = df["name"].str.strip().str.title()
df["city"] = df["city"].str.strip().str.title()
df["marks"] = pd.to_numeric(df["marks"], errors="coerce")   # "abc" becomes empty (NaN)
df = df.drop_duplicates(subset=["name", "city"])
bad = df[df["marks"].isna()]
print("Rows with missing or wrong marks:")
print(bad.to_string(index=False))
df = df.dropna(subset=["marks"])
df["marks"] = df["marks"].astype(int)
df.to_csv("students_clean.csv", index=False)
print("After:", len(df), "rows")
print(df.to_string(index=False))

Real output (19 October 2026):

Before: 5 rows
Rows with missing or wrong marks:
       name   city  marks
Amit Shinde   Pune    NaN
Rahul Patil Nashik    NaN
After: 2 rows
          name   city  marks
Priya Kulkarni   Pune     78
    Neha Joshi Nagpur     91

Look at what happened. Two students were removed because their marks were missing or wrong. That may be correct for a report, but those students still exist. The right next step is a human one: ask the teacher for Amit's and Rahul's marks. This is why our prompt said "print them first". AI-written code that quietly deletes data is the most dangerous kind.

6. Worked example 3: read a traceback and fix it

Suppose we write a small program to average some marks:

marks = input("Enter marks separated by commas: ").split(",")
total = sum(marks)
print("Average:", total / len(marks))

We type 78,91,64 and get this.

Real output (19 October 2026; we shortened the folder path):

Traceback (most recent call last):
  File "avg_bug.py", line 2, in <module>
    total = sum(marks)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

How to read a traceback, from the bottom up:

  1. The last line is the error type and message: TypeError, Python cannot add a number and text (str).
  2. The line above shows the exact code: total = sum(marks).
  3. "line 2" tells you where it is in your file.

The prompt (paste the whole traceback, not only the last line):

I got this error. Explain it simply, point to the line, and give me a hint, not the fix.
[paste the full traceback and your code here]

Expected output (yours will be similar, not the same): "input() always gives you text. After split, marks is a list of text pieces like '78', not numbers. sum cannot add text. Hint: turn each piece into a whole number before adding."

Now try the fix yourself:

marks = input("Enter marks separated by commas: ").split(",")
numbers = [int(m) for m in marks]   # turn each text piece into a number
total = sum(numbers)
print("Average:", round(total / len(numbers), 2))

Real output with 78,91,64 (19 October 2026):

Average: 77.67

Then test a bad input on purpose. We typed 78, 91, sixty:

    numbers = [int(m) for m in marks]   # turn each text piece into a number
               ~~~^^^
ValueError: invalid literal for int() with base 10: ' sixty'

A new error, and a new lesson: real users type words and spaces. Ask your tutor: "How do I show a friendly message instead of crashing when someone types a word?" (The answer involves try and except, a good next topic.)

7. The 4-step habit for every error

  1. Read the last line of the traceback first, and say the error type out loud.
  2. Find your line in the traceback and look at it before asking anyone.
  3. Ask AI for a hint, pasting the full traceback and the code.
  4. Fix it yourself, run it again, and then ask "how could I have avoided this?"

8. What AI gets wrong when it teaches Python

  • Too much at once: a 60-line answer for a 10-line problem. Ask for "the shortest version a beginner can understand".
  • Packages you have not installed: check every import line; install with pip install name if needed.
  • Old or invented functions: if Python says a function does not exist, tell AI the exact error and your Python version (python --version).
  • Confident but wrong maths: always check the first result by hand, like we did with the bill.
  • Code that hides problems: like deleting bad rows without telling you. Ask it to print what it removes.

9. Beginner mistakes and quick fixes

Mistake What happens Quick fix
"Write the whole program for me" You copy and learn nothing Use the tutor prompt; one step at a time
Pasting only the last line of an error AI guesses the wrong cause Paste the full traceback and the code
Running code without reading it Surprises, sometimes deleted data Say what each line will do before running
Not checking the output Wrong totals go unnoticed Check the first result by hand
Pasting real customer data into AI Privacy risk Use made-up sample rows
Giving up after one error No progress Errors are normal; use the 4-step habit

10. Try at home

Try at home

Task 1: your own bill calculator

  1. Open Google Colab and start a new notebook.
  2. Paste the tutor prompt into ChatGPT with "a bill calculator for a fruit stall".
  3. Build it step by step and check the total by hand.

Task 2: clean a small CSV

  1. Make a CSV with 6 rows and 3 mistakes on purpose (spaces, a repeat, a missing value).
  2. Ask AI for pandas code that prints what it removes.
  3. Compare the before and after counts.

Task 3: break it and fix it

  1. Run the average program and type a word instead of a number.
  2. Read the traceback from the bottom up.
  3. Ask AI for a hint, then add a friendly error message yourself.

Recap

In short

  1. Use AI as a tutor, not a ghost-writer: ask for one small step at a time.
  2. Google Colab runs Python in your browser for free; install Python on your laptop when you need your own files.
  3. Before running any line, say what you think it will do.
  4. Check the first result of every program by hand.
  5. Ask AI-written code to print what it removes or changes, never to delete silently.
  6. Read a traceback from the bottom: error type, then your line.
  7. Paste the full traceback and the code, and ask for a hint before the fix.
  8. Use made-up sample data, not real customer details.

Write one 10-line program this week, break it on purpose, and fix it with a hint instead of a solution. Every error you understand is a lesson you keep.

Previous chapter: Vibe Coding for Beginners: Build a Website with AI (No Coding Needed)

Next chapter: AI Coding Tools Compared: GitHub Copilot, Cursor and Claude Code


Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. The shop, students and marks on this page are made up for learning. Google Colab details were checked on Google's Colab pages on 19 October 2026. The Python output was produced on 19 October 2026 with Python 3.13 and pandas 3.0. AI output changes every time, so your output will be similar, not the same.