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.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

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.

SECTION 2

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).

SECTION 3

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.

Lifecycle of Running a Python File1. TEXT EDITORWrite your codeprint("Hello")2. SAVE FILEhello.py(.py extension)3. TERMINAL$ python hello.py(invoke interpreter)4. INTERPRETERReads lineby lineSUCCESSHelloERRORTraceback...orExample Traceback Message:Traceback (most recent call last): File "hello.py", line 1, in <module> prnt("Hello")NameError: name 'prnt' is not defined
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.

SECTION 4

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.

SECTION 5

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.

Common Python Errors at a GlancePython TracebackSyntaxErrorGrammar mistake in codeNameErrorUndefined variable or typoTypeErrorWrong data type usedMissing colon :Unmatched ( or "Bad indentation= instead of ==Wrong keywordMisspelled variableprnt vs printUsing before definingCase sensitivity"3" + 5str + int mismatchWrong # of argsto a functionReading Strategy: Read Bottom → TopNameError: name 'prnt' is not defined← Start here! Error type + description prnt("Hello")← The offending line of code File "hello.py", line 1← Which file and line number
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.
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

Quick reference for the five most common beginner Python errors

SECTION 6

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. 1

    Step 1 — Create the File

    Open 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. 2

    Step 2 — Run the File in the Terminal

    Open 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. 3

    Step 3 — Read the Traceback

    Instead 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. 4

    Step 4 — Fix the Bug

    Looking 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. 5

    Step 5 — Run Again and Verify

    Save 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.

SECTION 7

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.

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

Comparison of common methods for running Python code

✦

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.

SECTION 8

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.

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

How beginner concepts grow into advanced skills

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.

SECTION 9

Practice Problems

Question 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?
Show answer
A SyntaxError occurs during the parsing phase, before any of your code actually runs. This means that if you have a syntax error anywhere in your file, no lines will execute at all — not even the ones above the error. A NameError is a runtime error that only occurs when the interpreter reaches the specific line that references an undefined name. Lines of code above the problematic line will have already executed successfully. This distinction is important because it affects your debugging strategy: with a SyntaxError you know nothing ran, but with a NameError the program may have already produced partial output.

Question 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?
Show answer
Python will display a NameError: name 'mesage' is not defined pointing to line 2. The variable was defined as message (with two s's) but line 2 misspells it as mesage (one s). Python is case-sensitive and spelling-sensitive, so it treats these as two different names. The fix is to change line 2 to print(message). Always compare the exact spelling in the error message to your variable definitions.

Question 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?
Show answer
Python will raise a TypeError: can only concatenate str (not "int") to str on line 2. The input() function always returns a string, so age holds the string "16", not the integer 16. When Python tries to add 10 (an integer) to "16" (a string), it cannot combine those types. The fix is to convert the input to an integer on line 1: age = int(input("Enter your age: ")). Now age will hold 16 as an integer, and the addition on line 2 will work correctly.

Question 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.
Show answer
The traceback tells us that on line 5 of quiz.py, the variable total holds the value 0, causing a ZeroDivisionError when the program tries to compute correct / total. You should investigate how total gets its value — it might be set to 0 by default or come from user input that was not validated. A general prevention strategy is to add a guard clause before the division, such as if total != 0:, and provide an alternative message (e.g., "No questions answered yet") when total is zero. This pattern of checking before performing a risky operation is a fundamental defensive programming practice.

Question 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.
Show answer
The different behaviors come from when each error is detected. A SyntaxError is caught during parsing, which happens before execution begins. Python scans the entire file for grammar correctness first, so if any line has a syntax problem, no lines execute at all — that's why your friend sees no output. A NameError is a runtime error, detected only when the interpreter actually reaches the problematic line during execution. Your first 14 lines ran normally because they contained no errors. As for correctness: a program that produces no errors is not necessarily correct. It might run without crashing but produce wrong output — this is called a logic error (or semantic error). For example, a program that calculates a tip as total - 0.2 instead of total * 0.2 will run without any traceback but give the wrong answer. Logic errors are often harder to find than syntax or runtime errors because Python cannot detect them for you.

SUMMARY

Lesson Summary

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