COMPUTER PROGRAMMING 1 (PYTHON) • PYTHON FUNDAMENTALS

Running Python Files — I can create and run a Python file and interpret basic interpreter/traceback messages at my level.

Learn to create, save, and execute Python scripts while decoding the error messages that guide you toward working code.

Historical Context & Motivation

Before modern programming languages existed, early computer scientists had to feed instructions into machines using punched cards or toggle switches — there was no concept of a "file" you could simply double-click to run. The idea of storing a program in a human-readable text file and then handing it to an interpreter to execute line by line was a major leap forward. Python, created by Guido van Rossum in the late 1980s, was designed from the start to make this process as simple and beginner-friendly as possible.

1950s
Batch Processing Era
Programs were submitted on punched cards and fed into mainframes. Errors appeared as cryptic printouts that could take hours or days to receive back.
1970s
Rise of Text Editors & Terminals
Programmers began writing source code in plain text files using editors like vi and Emacs, then running those files through compilers or interpreters directly from the command line.
1991
Python 0.9 Released
Guido van Rossum published the first version of Python, emphasizing readability and clear error messages. The .py file extension became the standard for Python scripts.
2008
Python 3 Arrives
Python 3 modernized the language and improved its traceback messages, making error descriptions more descriptive and beginner-friendly.
2020s
Modern Python & Enhanced Errors
Python 3.10+ introduced even more detailed error messages — including suggestions like "Did you mean...?" — reducing the frustration of debugging for newcomers.

The big question this lesson addresses is straightforward but essential: how do you go from a blank screen to running your own Python program, and what do you do when something goes wrong? Understanding how to create a .py file, execute it, and read the interpreter's feedback is the very first skill every Python programmer needs.

Core Principles & Definitions

Before you write a single line of code, you need to understand a handful of foundational ideas. These concepts form the mental framework for everything you will do in Python.

1

Python Script (.py File)

A Python script is a plain text file saved with the .py extension. It contains Python instructions that the interpreter reads from top to bottom.
2

The Python Interpreter

The interpreter is the program that reads your script line by line, translates each instruction into machine code, and executes it immediately. You invoke it with the python (or python3) command.
3

The Terminal / Command Line

The terminal (also called the command line or shell) is the text-based interface where you type commands to run your scripts. On macOS it's Terminal, on Windows it's Command Prompt or PowerShell.
4

Syntax Errors vs. Runtime Errors

A syntax error means Python cannot understand your code (like a grammar mistake). A runtime error means the code is grammatically correct but something goes wrong while running.
5

Traceback Messages

A traceback is Python's error report. It shows the file name, the line number, the offending code, and a description of what went wrong — essentially a roadmap to your bug.
✦ KEY TAKEAWAY
Think of a Python script like a recipe card and the interpreter like a chef. The chef reads your recipe step by step and follows each instruction. If the chef hits a line that doesn't make sense — like "bake at purple degrees" — they stop and tell you exactly which line confused them. That's a traceback message. Learning to read the chef's complaints is half the battle of cooking (or coding).

Visual Explanation — From File to Output

The diagram below shows the complete lifecycle of running a Python file. You start by writing code in a text editor, save it as a .py file, tell the interpreter to run it via the terminal, and the interpreter either produces output or gives you an error message.

The flow moves from left to right: you write code in a text editor, save it as a .py file, run it from the terminal, and the interpreter either produces output (success) or a traceback (error). The bottom panel shows what a real traceback looks like.

Notice that the interpreter always tells you two critical pieces of information when an error occurs: the line number where the problem was detected and the type of error (such as NameError or SyntaxError). These two clues are your starting point for fixing any bug.

How the Interpreter Processes Your File

When you type python hello.py in the terminal and press Enter, a specific sequence of events happens inside the Python interpreter. Understanding this process helps you predict what the interpreter will do and why certain errors appear.

Step-by-Step: What Happens When You Hit Enter

  1. Lexing (Tokenizing) — The interpreter breaks your source code into small chunks called tokens: keywords like print, symbols like (, and literal values like "Hello".
  2. Parsing — The tokens are checked against Python's grammar rules. If a rule is broken (e.g., a missing parenthesis), a SyntaxError is raised before any code runs.
  3. Compiling to Bytecode — If the grammar checks pass, Python compiles your source into an intermediate form called bytecode. This bytecode is what actually gets executed.
  4. Execution — The Python Virtual Machine (PVM) runs the bytecode line by line. If something goes wrong during execution (e.g., dividing by zero), a runtime error is raised with a traceback.
⚠️ Syntax Errors Are Caught Early
A SyntaxError happens during the parsing phase — before your program actually runs. This means not a single line of your code executes if there is a syntax error anywhere in the file. Runtime errors like NameError or TypeError, on the other hand, only appear when the interpreter reaches the problematic line during execution.

Anatomy of a Traceback Message

A traceback has three main parts. The first line always says Traceback (most recent call last):. The middle section shows you the file name, line number, and the actual line of code that caused the error. The last line gives you the error type and a short description. Always read tracebacks from bottom to top — the most important information is at the end.

Common Error Types & How to Read Them

As a beginning Python programmer, you will encounter a few error types over and over. Learning to recognize them quickly will save you a lot of time. The diagram below maps the most common errors to their typical causes, and the table that follows gives you a quick reference you can come back to again and again.

The three most common beginner errors — SyntaxError, NameError, and TypeError — branch into their typical causes. The bottom panel shows the recommended bottom-to-top reading strategy for tracebacks.
Quick reference for the five most common beginner Python errors
Error TypeWhen It HappensCommon CauseQuick Fix
SyntaxErrorBefore any code runs (parsing phase)Missing colon, unmatched parenthesis, or bad indentationCheck the line number indicated and look for typos or missing punctuation
NameErrorDuring execution (runtime)Misspelled variable or function name, or using a variable before defining itCompare the name in the error to your actual code — check spelling and case
TypeErrorDuring execution (runtime)Mixing incompatible types (e.g., adding a string to a number)Use int(), str(), or float() to convert types
IndentationErrorBefore any code runs (parsing phase)Inconsistent spaces/tabs or missing indentation after a colonUse consistent 4-space indentation throughout your file
ZeroDivisionErrorDuring execution (runtime)Dividing a number by zeroAdd a check: if x != 0: before dividing

Worked Example — From Broken Code to Working Program

Let's walk through the full process of creating a Python file, encountering an error, reading the traceback, and fixing the code. Imagine you are a student who just installed Python and wants to create a small program that greets a user by name.

Creating and Debugging greet.py
1
Step 1 — Create the FileOpen a text editor (such as VS Code, IDLE, or even Notepad). Type the following code and save the file as greet.py in a folder you can easily find (for example, your Desktop). name = input("What is your name? ") print("Hello, " + name + "! Welcome to Python."
File saved as greet.py
2
Step 2 — Run the File in the TerminalOpen the terminal. Navigate to the folder containing greet.py using the cd command (for example, cd Desktop). Then type: python greet.py
Command entered — waiting for interpreter response
3
Step 3 — Read the TracebackInstead of a greeting, Python prints this error: File "greet.py", line 2 print("Hello, " + name + "! Welcome to Python." ^ SyntaxError: unexpected EOF while parsing Reading from the bottom: the error type is SyntaxError, and the description says "unexpected EOF while parsing." EOF stands for End Of File — Python reached the end of your code while still expecting something. The caret (^) points to where Python got confused.
SyntaxError on line 2 — missing closing parenthesis
4
Step 4 — Fix the BugLooking at line 2, you can see the print() call opens a parenthesis but never closes it. Add the missing ) at the end of line 2: name = input("What is your name? ") print("Hello, " + name + "! Welcome to Python.")
Closing parenthesis added — bug fixed
5
Step 5 — Run Again and VerifySave the file and run python greet.py again. This time the program asks for your name and responds: What is your name? Alex Hello, Alex! Welcome to Python.
Program runs successfully — output is correct
💡 Pro Tip: Save Before Running
One of the most common beginner mistakes is editing your file but forgetting to save before running it again. The interpreter always reads the version of the file that is saved to disk, not what is currently on your screen. If your fix doesn't seem to work, double-check that you pressed Ctrl+S (or Cmd+S on Mac) before switching to the terminal.

Ways to Run Python — Comparing Your Options

There is more than one way to execute Python code, and each has its strengths and weaknesses. As a beginner, it helps to know the differences so you can choose the right tool for the job.

Comparison of common methods for running Python code
MethodHow It WorksBest ForLimitations
Running a .py file from the terminalType python filename.py in the command lineFull programs, scripts, and projectsRequires comfort with the terminal and file navigation
Python interactive shell (REPL)Type python with no file name to open the interactive prompt >>>Quick experiments, testing one-linersCode is not saved — lost when you close the shell
IDLE (bundled with Python)A simple IDE that comes with every Python installation; includes an editor and a shellAbsolute beginners who want a graphical interfaceLimited features compared to modern editors
VS Code / PyCharmFull-featured editors with built-in terminal, syntax highlighting, and run buttonsLarger projects and professional workflowsCan feel overwhelming at first with many menus and settings
Online platforms (Replit, Google Colab)Write and run Python in a web browser with no installationSchool Chromebooks, quick sharing, collaborationRequires internet; limited access to local files
✦ KEY TAKEAWAY
Think of these tools like different kitchens. The interactive shell is a microwave — fast and great for reheating leftovers (testing tiny code snippets). Running a .py file from the terminal is using a full oven — the standard way to cook a complete meal (build a real program). An IDE like VS Code is a professional kitchen with all the gadgets — powerful, but you don't need everything on day one.

Connection to Advanced Topics

The skills you are building right now — creating files, running them, and reading error messages — scale directly into more advanced programming. As your programs grow, the concepts evolve but the foundations stay the same.

How beginner concepts grow into advanced skills
What You Learn NowWhat It Becomes Later
Running a single .py fileRunning multi-file projects with modules, packages, and import statements
Reading a basic tracebackNavigating complex stack traces that span multiple files and using debuggers to step through code
Fixing SyntaxError and NameErrorHandling exceptions with try/except blocks and writing custom error classes
Using the terminal to run scriptsUsing command-line arguments, virtual environments, and automation scripts
Saving output to the console with print()Logging output to files, sending data over networks, and building graphical user interfaces

Every professional programmer still reads error messages and tracebacks daily. The difference is that experienced developers have seen enough errors that they can diagnose problems quickly. By practicing these fundamentals now, you are building the pattern recognition that will make debugging feel natural rather than frustrating.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain the difference between a SyntaxError and a NameError. At what stage of execution does each one occur, and what does that mean for the rest of your program?
PROBLEM 2 — BASIC
You save the following code in a file called test.py and run it with python test.py: message = "Hello" print(mesage) What error will Python display, and what is the fix?
PROBLEM 3 — INTERMEDIATE
You run python calc.py on the following code: age = input("Enter your age: ") future_age = age + 10 print("In 10 years you will be " + str(future_age)) The user types 16. What happens, and how do you fix it?
PROBLEM 4 — APPLIED
A friend sends you a Python file called quiz.py and you see this traceback when running it: Traceback (most recent call last): File "quiz.py", line 5, in <module> score = correct / total ZeroDivisionError: division by zero Using only the traceback (without seeing the full code), describe what went wrong, which line to investigate, and suggest a general strategy to prevent this kind of error.
PROBLEM 5 — CRITICAL THINKING
Consider this scenario: you write a 20-line Python script. When you run it, lines 1 through 14 execute perfectly and produce correct output. Then you get a NameError on line 15. Your friend writes a different 20-line script and gets a SyntaxError on line 15 — but none of their output appears. Explain why the two errors behave so differently, and discuss whether a program that runs without errors is necessarily a correct program.

Lesson Summary

In this lesson you learned the complete workflow for running Python programs. You create a Python script by writing code in a text editor and saving it with the .py extension. You execute it by typing python filename.py in the terminal. The Python interpreter reads your file line by line, first checking for syntax errors during parsing and then watching for runtime errors during execution.

When something goes wrong, the interpreter produces a traceback message that tells you the file name, line number, the problematic code, and the error type. You read tracebacks from bottom to top to quickly find the cause. The most common beginner errors are SyntaxError (grammar mistakes), NameError (misspelled names), and TypeError (mixing incompatible data types). Mastering this create-run-debug cycle is the foundation for everything you will build in Python.

Varsity Tutors • Computer Programming 1 (Python) • Running Python Files