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

Run a Python File and Read the Error: Tracebacks in Three Steps

Run a file two ways, then break it on purpose. A NameError, an IndentationError, a TypeError and a three-frame traceback across two files, all read the same way: last line, line number, fix.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Run a file with the Run button or with python in the Terminal, and read the exit code
  • Name every part of a traceback
  • Read any error in the same order: last line, line number, fix
  • Follow a traceback across two files and hand an error to an AI tool the right way

Before you start

  • Set Up PyCharm for Python
  • Your First Python Program

Code breaks all the time, even for experienced developers. So reading errors is a skill you'll use every single day. In this lesson you'll run a file two ways, break it on purpose, and learn to read an error message the same way every time, so an error stops feeling scary.

Two ways to run a file

print("Hello from run_me.py")
total = 2 + 3
print("Total:", total)

The first way is the green Run button in PyCharm. The second is the Terminal. PyCharm has one built in that opens in your project folder. Type python, a space and the file name, then press Enter:

python run_me.py
Hello from run_me.py
Total: 5

Both ways give the same two lines, because both do the same job: they hand your file to Python. On a Mac, if python isn't found, try python3. Use whichever you like, but try the Terminal sometimes, because you'll see these commands everywhere.

The exit code

The last line in the Run window says the process finished with exit code 0. When a program ends, it hands back one number to whatever started it. Zero means it finished without a problem. Anything else means something went wrong. You never type this number, but other tools read it to know whether a run worked.

The first broken file

price = 20
print("Price:", prise)
Traceback (most recent call last):
  File "S01L03_1_ReadErrors\name_error.py", line 2, in <module>
    print("Price:", prise)
                    ^^^^^
NameError: name 'prise' is not defined. Did you mean: 'price'?

Line one works, so price holds 20. Line two asks for prise, with an s. Python has no such name, so it stops right there. All that red text is called a traceback, and the exit code is now 1. Python isn't telling you off. It's telling you what went wrong, and where.

The parts of a traceback

The parts of a Python traceback: the heading, the file and line number, the code line, the marks pointing at the problem, and the last line with error type and message Traceback (most recent call last): File "name_error.py", line 2 print("Price:", prise) ^^^^^ NameError: name 'prise' is not ... the trail, newest at the bottom which file, which line the code Python was running marks point at the trouble error type : message (read first) Read order: last line, then the line number above it, then fix.
Every traceback has the same parts. Start at the bottom.
  • Traceback (most recent call last) means "here's the trail, and the newest step is at the bottom".
  • The file line names the file (on your machine, the full path; in the Run window you can click it to jump there) and the line number. in <module> just means the top level of the file.
  • Then comes the exact code line Python was running.
  • The marks underneath point at the spot that caused the trouble: prise.
  • The last line has the error type, NameError, and after the colon, the message. Python even suggests price.

The reading order: last line, line number, fix

  1. Read the last line. NameError, prise is not defined. Now you know what went wrong.
  2. Find the line number just above it: line 2 of name_error.py. Now you know where.
  3. Fix it.
price = 20
print("Price:", price)
Price: 20

Exit code 0 again. It's tempting to start at the top and get lost, so start at the bottom.

Same order, an IndentationError

You haven't met if yet, so don't worry how it works. All you need today: a line ending in a colon needs an indented line under it, and line 3 isn't indented.

age = 20
if age >= 18:
print("Adult")
  File "S01L03_1_ReadErrors\indent_error.py", line 3
    print("Adult")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

Last line: an indented block was expected after the if on line 2. Line number: the file line says line 3. Fix: put four spaces in front of print, and the fixed file prints Adult with exit code 0.

Notice there's no Traceback heading this time. Python checks the layout of the whole file before it runs anything. This file failed that check, so not even line 1 ran.

Same order, a TypeError

age = 20
print("Age: " + age)
Traceback (most recent call last):
  File "S01L03_1_ReadErrors\type_error.py", line 2, in <module>
    print("Age: " + age)
          ~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

Last line: str is Python's short name for a string, int is a whole number, and concatenate means join. Python can join text to text, but not text to a number. Line number: line 2, and the marks point right at the plus sign. Fix: str(age) turns 20 into text.

age = 20
print("Age: " + str(age))
Age: 20

Three different errors, the same three steps.

What the error type tells you

Error typeLook for
NameErrora name Python doesn't know: a typo, or a variable not created yet
IndentationErrorwrong spaces at the start of a line
TypeErrora value of the wrong type for what you're doing
SyntaxErrorPython can't understand how the line is written
ValueErrorright type, unusable value, like turning a word into a number

You don't have to memorise these. You'll meet them again and again.

An error across two files

Bigger programs have tracebacks with several steps. Picture a restaurant. You order at the counter, the counter asks the kitchen, the kitchen asks the store room for tomatoes, and there aren't any. The bad news travels back along the same path to you. To solve it, you go to where it went wrong: the store room.

Here's that in code. You haven't covered functions yet, so take them as given: a function is a named piece of code that another line can call.

# helper.py
def add_tax(price):
    return price * (1 + tax_rate)


def final_price(price):
    return round(add_tax(price), 2)
# app.py
from helper import final_price

print("Starting")
print(final_price(40))
Starting
Traceback (most recent call last):
  File "S01L03_1_ReadErrors\app.py", line 4, in <module>
    print(final_price(40))
          ~~~~~~~~~~~^^^^
  File "S01L03_1_ReadErrors\helper.py", line 6, in final_price
    return round(add_tax(price), 2)
                 ~~~~~~~^^^^^^^
  File "S01L03_1_ReadErrors\helper.py", line 2, in add_tax
    return price * (1 + tax_rate)
                        ^^^^^^^^
NameError: name 'tax_rate' is not defined

app.py line 4 is the counter asking the kitchen. final_price on line 6 of helper.py asks add_tax, the store room. And add_tax on line 2 needs tax_rate, which nobody ever created. Those are the missing tomatoes. Notice Starting did print, because that line ran before the error.

Reading several frames

Each file line with its code is called a frame. Nothing about the method changes:

  • Last line: tax_rate is not defined.
  • The frame closest to the bottom, helper.py line 2, is where it broke.
  • Moving up, helper.py line 6 called it, and above that app.py line 4 is where it all started.

That's what "most recent call last" means: oldest step at the top, newest at the bottom. The fix is one line at the top of the helper, tax_rate = 0.1. With that in a fixed copy, the run prints:

Starting
44.0

Forty with ten percent tax is 44.0, exit code 0. One tip: the bottom frame is the first place to look, but it isn't always where the fix goes. Sometimes a function is fine and a wrong value came in from the frame above. If the bottom line looks correct, go up one frame and check what was passed in.

Handing an error to an AI tool

AI tools are good with errors if you give them the right things. A lot of people paste only the last line and write "fix this". Do this instead:

  1. Copy the whole traceback, first line to last.
  2. Paste every file the traceback names; here, app.py and helper.py.
  3. Ask one question: "What does this error mean? Don't fix it yet."

Before you paste anything, take out passwords and keys. A traceback rarely has them, but your code might.

Why the meaning first? Because you've done the reading yourself, so you can check the answer. A good answer names tax_rate and points at helper.py line 2. If it matches, ask "Show me the smallest fix, and explain it." Then run again. Exit code 0 says it finished cleanly; it doesn't prove the answer is right, so read the output too. The AI tool helps, but the reading stays with you.

Quick recap

StepWhat you do
RunRun button, or python file.py in the Terminal
Exit code0 is a clean finish, anything else a problem
Readlast line, line number, fix
Several framesstart at the bottom, go up to see how you got there
AI helpwhole traceback plus the code, ask for the meaning first

Try it yourself

city = "Pune"
temp = 31
print("City:", city)
print("Temp:", temp)
City: Pune
Temp: 31

Break try_it.py on purpose by misspelling a name, read the message in that order, fix it, and look for exit code 0.

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 · 5 of 48

Previous
Set Up PyCharm for Python: Install, First Project and First Run
Next post
Python Data Types, Variables and Strings: Indexing, Slicing and f-strings

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

  • Two ways to run a file
  • The exit code
  • The first broken file
  • The parts of a traceback
  • The reading order: last line, line number, fix
  • Same order, an IndentationError
  • Same order, a TypeError
  • What the error type tells you
  • An error across two files
  • Reading several frames
  • Handing an error to an AI tool
  • 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.