30 min read

> "The only way to learn a new programming language is by writing programs in it."

Prerequisites

  • 1
  • A computer running Windows, macOS, or Linux with internet access

Learning Objectives

  • Install Python 3.13+ and VS Code on your operating system
  • Write, save, and run a Python program from the terminal and from VS Code
  • Use the Python interactive interpreter (REPL) to experiment with code
  • Identify and fix common first-program errors (syntax errors, indentation, file naming)
  • Use print() and input() to create interactive programs

Chapter 2: Getting Started: Python, VS Code, and Your First Program

"The only way to learn a new programming language is by writing programs in it." — Brian Kernighan and Dennis Ritchie, The C Programming Language (1978)

Chapter Overview

In Chapter 1, we talked about what computer science is — the thinking behind the code. Now it's time to actually write some code.

By the end of this chapter, you'll have Python installed on your machine, you'll know how to use the terminal to navigate your file system and run programs, and you'll have written several working programs — including the first version of TaskFlow, the project you'll build across this entire course. More importantly, you'll understand what's happening when you run a program, not just how to click the right buttons.

This chapter is hands-on. You'll spend most of your time with your hands on the keyboard, trying things, breaking things, and fixing things. That's exactly how it should be.

In this chapter, you will learn to: - Install Python 3.13 or later (the newest stable release is recommended) and verify the installation works - Navigate the terminal using basic commands - Use the Python REPL to experiment with code interactively - Write, save, and run .py script files - Use print() to display output and input() to get user input - Write comments that help humans understand your code - Identify and fix common first-program errors

🏃 Fast Track: If you already have Python 3.13+ and VS Code installed, skip to section 2.4 (Your First Python Program). If you're also comfortable with the terminal, skip to section 2.7 (print() — Making Python Talk).

🔬 Deep Dive: After this chapter, read Appendix B for additional environment setup details — virtual environments, alternative editors, and platform-specific troubleshooting.


2.1 What Is Python?

Python is a programming language created by Guido van Rossum, who started work on it in December 1989 and released the first public version in 1991. He named it after Monty Python's Flying Circus, not the snake — which tells you something about the culture around this language. Python was designed from the start to be readable. Van Rossum wanted a language where the code looked almost like English pseudocode, where you could glance at a program and understand what it does even before you know the language well.

That design philosophy is why Python has become the most popular language for teaching introductory CS. It's also why it dominates in data science, machine learning, web development, automation, and scientific computing. Python isn't a "beginner language" — it's a professional tool used by Google, NASA, Instagram, Spotify, and thousands of other organizations.

Why Python for This Course?

Three reasons:

  1. Readability. Python uses indentation to show structure (instead of curly braces like C or Java), which forces you to write clean, organized code from day one. We'll see exactly how this works later in this chapter.

  2. Breadth. Python is genuinely useful in almost every area of computing. Whatever direction you go after this course — web development, data science, AI, game development, systems administration — Python will be relevant.

  3. Ecosystem. Python has a massive collection of libraries (pre-written code you can use) for everything from building websites to analyzing DNA sequences. Dr. Patel from Chapter 1? She uses Python every day to process genomic data, precisely because the tools she needs already exist.

What Kind of Language Is Python?

Python is an interpreted language. This distinction matters, so let's unpack it.

Some languages (like C or Rust) are compiled: you write the code, run a compiler that translates it into machine code (the binary instructions your CPU understands), and then run the resulting program. The compilation step happens once; after that, the program runs directly on the hardware.

Python works differently. When you run a Python program, the Python interpreter — itself just a program — takes your source file and runs it for you. Under the hood it does two quick things: it first reads the whole file, checks the grammar, and translates it into a compact intermediate form called bytecode; then it executes that bytecode one instruction at a time, top to bottom. Both steps happen automatically every time you type python myfile.py. There's no separate compile step for you to run and no executable file to manage — you write code and run it.

That first "check the whole file" step has a practical consequence you'll meet in section 2.10: if line 50 of your program has a grammar mistake, Python refuses to run any of it — not even line 1. Other kinds of mistakes only show up when Python actually reaches the faulty line.

This has trade-offs. Interpreted languages are generally slower than compiled ones because of the translation overhead. But they're much faster to develop in, because you can write a line of code and see the result instantly, without waiting for a compiler. For learning, for prototyping, and for the kinds of programs we'll write in this course, that instant feedback loop is far more valuable than raw speed.

💡 Intuition: Think of the difference between a compiled language and an interpreted language like the difference between translating a whole book into another language (compilation) versus having a live translator who converts each sentence as the speaker says it (interpretation). The book translation is faster to read once it's done, but the live translation lets you start communicating immediately.


2.2 Installing Python

Let's get Python on your machine. The process is slightly different on each operating system, so find your section below and follow the steps.

⚠️ Common Pitfall: Your computer might already have some Python on it — installed by another program, by your school's IT department, or bundled with developer tools — and it may well be an older version. (Python 2, which you'll still see in old tutorials, reached end-of-life in 2020; don't use it.) We need Python 3.13 or later for this book. Install from the official source to be sure.

Windows

Since Python 3.14, the officially recommended way to install Python on Windows is the Python install manager, a small tool that downloads Python for you and keeps it up to date.

  1. Open your web browser, go to python.org/downloads, and download the Python install manager. (It's also in the Microsoft Store under the same name.)
  2. Run it and accept the defaults. If it asks whether to add a directory to your PATH, say yes — the PATH is the list of folders your terminal searches when you type a command name.
  3. Open the Command Prompt (press Win+R, type cmd, press Enter) and type:
python --version

The first time, the install manager may need a minute to download the latest Python before it answers. Then you should see something like:

Python 3.14.0

(Your exact numbers will differ — any version 3.13 or later is fine.) If instead you get "'python' is not recognized as an internal or external command," or the Microsoft Store pops open, click Start, search for "Manage app execution aliases," and make sure the "Python (default)" aliases are switched on. Then close and reopen Command Prompt.

📝 Note: the classic installer. python.org still offers the older "Windows installer (64-bit)" .exe for now (it is deprecated, and won't be produced for Python 3.16 or later). If you use it, check the box that says "Add python.exe to PATH" on the first screen. Missing that checkbox is the single most common Windows installation problem: the terminal simply can't find Python. If that happens, run the installer again and tick the box.

macOS

  1. Go to python.org/downloads and download the macOS installer.
  2. Run the .pkg file and follow the prompts.
  3. Open Terminal (Applications → Utilities → Terminal, or press Cmd+Space and search for "Terminal").
  4. Type:
python3 --version

You should see:

Python 3.13.2

⚠️ Common Pitfall (macOS): On macOS, the command is python3, not python. Apple removed the old built-in Python 2.7 in macOS 12.3 (2022), and nothing replaced it under the name python, so typing just python at a stock Terminal prompt will usually return "command not found." Throughout this book, when we say "type python," macOS users should type python3 instead.

Linux (Ubuntu/Debian)

Most Linux distributions come with Python 3 pre-installed. Check which version you have first:

python3 --version

If it says 3.13 or later — as it will on Debian 13 and Ubuntu 25.04 or newer — you're done. Ubuntu 24.04 LTS ships Python 3.12, and its standard repositories don't include 3.13, so you'll need the widely used "deadsnakes" package archive:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.13 python3.13-venv

This installs Python 3.13 alongside the system's Python rather than replacing it (Ubuntu's own tools depend on the system version, so leave that one alone). Run it as python3.13:

python3.13 --version

Whenever this book says python, type python3.13 instead.

Verifying Your Installation

Regardless of your OS, run this command in your terminal:

python --version

(Or python3 --version on macOS/Linux.) You need Python 3.13 or higher. If the number after 3. is 13 or bigger, you're all set. If you see 3.12 or older, install a newer version as described above. (Python 3.9 reached end-of-life in October 2025, meaning it no longer gets security fixes.)

✅ Action Checklist: Python Installation

  • [ ] Installed Python from python.org (or your Linux package manager)
  • [ ] Said yes to adding Python to PATH (Windows only)
  • [ ] Opened a terminal
  • [ ] Ran python --version and confirmed 3.13+

2.3 The Terminal: Your New Best Friend

If you've only ever used a computer through its graphical interface — clicking icons, dragging files — the terminal might feel like stepping into the 1980s. No icons. No mouse. Just a blinking cursor waiting for you to type a command.

But here's the thing: the terminal is one of the most powerful tools you'll ever learn. Every professional developer uses it daily. It's faster than clicking through folders, it's scriptable (you can automate sequences of commands), and it gives you access to tools that have no graphical equivalent.

What Is the Terminal?

The terminal (also called the command line or console) is a text-based interface to your computer's operating system. Instead of double-clicking a folder to open it, you type a command. Instead of dragging a file to the trash, you type a command. It does the same things as the graphical interface, just with text.

The shell is the program running inside the terminal that interprets your commands. On macOS and Linux, the default shell is usually zsh or bash. On Windows, it's cmd.exe (Command Prompt) or PowerShell. They're all slightly different, but the core concepts are the same.

📝 Windows users: PowerShell (the shell you'll usually get in VS Code's terminal and in Windows Terminal) understands the macOS/Linux commands below — pwd, ls, cd ~ — as well as the Command Prompt ones. The classic Command Prompt (cmd.exe) only understands its own versions, which are shown alongside.

Essential Commands

You only need three commands to get started. You'll learn more over time, but these will carry you through the first several chapters.

pwd — Print Working Directory (macOS/Linux) or cd with no arguments (Windows)

This tells you where you are in the file system.

$ pwd
/Users/yourname/Documents

On Windows Command Prompt:

C:\Users\yourname\Documents>

(The prompt itself shows your location on Windows.)

ls — List Files (macOS/Linux) or dir (Windows)

This shows you what's in the current directory.

$ ls
Desktop    Documents    Downloads    Music    Pictures

On Windows:

C:\Users\yourname> dir

cd — Change Directory

This moves you to a different folder. It works the same on all platforms.

$ cd Documents
$ pwd
/Users/yourname/Documents

To go up one level (back to the parent folder):

$ cd ..

To go to your home directory:

$ cd ~

(The ~ is shorthand for your home folder. Command Prompt doesn't understand it; there, use cd %USERPROFILE% instead.)

Setting Up a Course Folder

Let's create a folder for all your work in this course. Open your terminal and type:

cd ~
mkdir cs1
cd cs1

(mkdir means "make directory" — it creates a new folder. It works in every shell, including Command Prompt. In Command Prompt, replace cd ~ with cd %USERPROFILE%.)

Now create a subfolder for this chapter:

mkdir ch02
cd ch02

You're now in ~/cs1/ch02. This is where we'll save our first programs.

💡 Intuition: Think of the terminal like texting your computer. Instead of pointing at things with a mouse, you describe what you want in words. It takes a bit of getting used to, but once you're comfortable, it's often faster than the graphical approach.

🔄 Check Your Understanding (try to answer without scrolling up)

  1. What does the cd command do?
  2. What's the difference between a terminal and a shell?
  3. How do you go "up" one directory level in the terminal?

Verify

  1. cd (change directory) moves you to a different folder in the file system.
  2. The terminal is the window/application you type into. The shell is the program running inside the terminal that interprets your commands (e.g., bash, zsh, cmd).
  3. cd .. — the two dots represent the parent directory.

2.4 Your First Python Program: The REPL

Now for the moment you've been waiting for. Open your terminal and type:

python

(Or python3 on macOS/Linux.)

You should see something like:

Python 3.13.2 (main, Feb  4 2025, 14:51:09)
[GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Those three arrows (>>>) are the Python REPL prompt. REPL stands for Read-Eval-Print Loop: Python reads what you type, evaluates it (runs it), prints the result, and loops back to wait for more input. It's an interactive playground where you can try things instantly.

Experimenting in the REPL

Type this and press Enter:

>>> print("Hello, World!")
Hello, World!

Congratulations. You've just written and executed your first line of Python. The print() function takes whatever you put inside the parentheses and displays it on the screen.

Try some more:

>>> 2 + 3
5
>>> 10 * 7
70
>>> "hello" + " " + "world"
'hello world'
>>> 2 ** 10
1024

The REPL is perfect for quick experiments. Wonder what 2 ** 10 does? Type it and find out. (It's exponentiation — 2 to the power of 10.) Wonder if you can multiply a string by a number? Try it:

>>> "ha" * 3
'hahaha'

You can! Python repeats the string. This kind of curiosity-driven exploration is exactly how experienced developers learn new features.

🔗 Connection: Remember computational thinking from Chapter 1? The REPL is decomposition in action. Instead of trying to write a whole program at once, you test small ideas one at a time. Professionals do this all the time — even developers with decades of experience fire up the REPL to test an idea before putting it in their code.

The Classic First Program

There's a tradition in programming, made famous by a 1978 book and a few years older than that (we'll explore its history in Case Study 1), where the first program you write in any new language simply prints "Hello, World!" to the screen. Let's honor that tradition:

>>> print("Hello, World!")
Hello, World!

In some languages, this takes multiple lines of boilerplate code. In Java, for instance, the Hello World program is:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

In Python, it's one line. That's part of Python's appeal — the language gets out of your way so you can focus on the problem. (Java itself got the message eventually: since Java 25, released in 2025, a beginner's file can shrink to a three-line void main() version.)

To exit the REPL, type:

>>> exit()

(Since Python 3.13, plain exit without the parentheses works too.) Or press Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows).

📊 Theme: Reading Code Is as Important as Writing It

Notice what just happened in the REPL. You typed an expression, and Python printed a result. You read that result and used it to understand what the expression does. This read-write cycle is fundamental. Throughout this course, you'll spend as much time reading code and output as you spend writing code — and that's not a sign that something is wrong. It's how the craft works.


2.5 Installing and Setting Up VS Code

The REPL is great for experimenting, but real programs live in files. To write, edit, and manage those files, you need a code editor. We'll use Visual Studio Code (VS Code) — a free editor from Microsoft, built on open-source code, that's become the most popular editor among professional developers.

An IDE (Integrated Development Environment) is a code editor on steroids: it combines a text editor, a terminal, a debugger, and other tools into one application. VS Code started as a lightweight editor but has grown into essentially a full IDE through its extension system.

Installing VS Code

  1. Go to code.visualstudio.com.
  2. Download the installer for your operating system.
  3. Run the installer with default settings. (On Windows, check "Add to PATH" if offered.)
  4. Open VS Code.

Installing the Python Extension

VS Code doesn't know about Python out of the box. You need to install an extension:

  1. Open VS Code.
  2. Click the Extensions icon in the left sidebar (it looks like four small squares).
  3. Search for "Python" in the search box.
  4. Install the extension by Microsoft (it should be the first result, with millions of downloads).
  5. Restart VS Code if prompted.

The Python extension gives you syntax highlighting (color-coding that makes code easier to read), code completion (VS Code suggests what you might type next), error detection, and a built-in way to run Python files.

Setting Up Your Workspace

  1. In VS Code, go to File → Open Folder.
  2. Navigate to the cs1 folder you created earlier and open it.
  3. In the left sidebar, you'll see your folder structure. Right-click on the ch02 folder and choose "New File."
  4. Name it hello.py. The .py extension tells VS Code (and your operating system) that this is a Python file.

You now have an empty Python file open in your editor. Let's put some code in it.

✅ Action Checklist: VS Code Setup

  • [ ] Downloaded and installed VS Code
  • [ ] Installed the Python extension
  • [ ] Opened your cs1 folder in VS Code
  • [ ] Created hello.py in the ch02 folder

2.6 Writing and Running Scripts

A script is a Python file — a text file with a .py extension that contains Python code. Unlike the REPL, where you type one line at a time, a script lets you write an entire program and run it all at once.

Your First Script

Type this into hello.py:

# My first Python script
print("Hello, World!")
print("My name is Python, and I'm here to help.")
print("Let's build something great together.")

Save the file (Ctrl+S on Windows/Linux, Cmd+S on macOS).

Running from the Terminal

Open a terminal (in VS Code, go to Terminal → New Terminal, or press Ctrl+`). VS Code's terminal starts in the folder you opened — cs1 — so move into the chapter folder:

cd ch02

(From any other terminal, cd ~/cs1/ch02 gets you there in one step.) Python looks for hello.py in the folder you're currently in, so this step matters: run the command from the wrong folder and you'll get can't open file ... No such file or directory.

Then run your script:

python hello.py

Output:

Hello, World!
My name is Python, and I'm here to help.
Let's build something great together.

That's it. You wrote a program, saved it to a file, and ran it. Every program you write in this course will follow this same pattern: write code in a .py file, save it, run it from the terminal.

Running from VS Code

You can also run the file directly in VS Code:

  1. Make sure hello.py is open in the editor.
  2. Click the "play" triangle (▶) in the upper right corner of the editor.
  3. VS Code opens a terminal panel at the bottom and runs your file.

Both methods do the same thing — VS Code's play button is just a shortcut for running python hello.py in the terminal. I recommend getting comfortable with both approaches, but especially the terminal method. It gives you more control and works the same way everywhere.

⚠️ Common Pitfall: Make sure you save the file before running it. If you type code and then run the file without saving, Python will run the old version. This is the source of many "but I changed it and nothing happened" moments. Get in the habit of pressing Ctrl+S before every run.


2.7 print() — Making Python Talk

You've already used print() several times, but let's understand it properly. print() is a built-in function — a tool that comes with Python, ready to use. Its job is simple: take whatever you give it and display it on the screen.

Basic Usage

print("Hello, World!")

Output:

Hello, World!

The text inside the quotes is called a string — a sequence of characters. The quotes tell Python "this is text, not a command." You can use single quotes or double quotes — Python treats them identically:

print("Hello, World!")   # double quotes
print('Hello, World!')   # single quotes — same result

Multiple Arguments

You can pass multiple items to print(), separated by commas:

print("My name is", "Elena", "and I love", "Python")

Output:

My name is Elena and I love Python

Notice that Python automatically puts a space between each item. That's the default behavior.

The sep Parameter

What if you don't want spaces between items? Or you want a different separator? Use the sep (separator) parameter:

print("2024", "01", "15", sep="-")

Output:

2024-01-15
print("apple", "banana", "cherry", sep=", ")

Output:

apple, banana, cherry
print("no", "spaces", "here", sep="")

Output:

nospaceshere

The end Parameter

By default, print() adds a newline at the end — each print() starts on a new line. You can change this with the end parameter:

print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")

Output:

Loading...

All four prints appear on the same line because the first three use end="" instead of the default newline.

A Preview of f-strings

We'll cover f-strings properly in Chapter 3, but here's a taste — they're too useful to wait:

name = "Elena"
print(f"Hello, {name}!")

Output:

Hello, Elena!

The f before the opening quote marks this as a formatted string. Anything inside {curly braces} gets replaced by its value. You'll use f-strings constantly throughout this course.

Anchor Example: Grade Calculator Banner

Let's reference our running example from Chapter 1. Here's the very first version of the grade calculator — it doesn't calculate anything yet, but it prints a welcome banner:

# grade_calculator.py — version 1.0 banner
print("=" * 40)
print("  Grade Calculator v1.0")
print("=" * 40)
print()
print("Welcome! This program will calculate")
print("your course grade from assignment scores.")

Output:

========================================
  Grade Calculator v1.0
========================================

Welcome! This program will calculate
your course grade from assignment scores.

Notice the trick: "=" * 40 repeats the = character 40 times. We saw string repetition in the REPL earlier — here it's being used to create a visual border. Also notice print() with no arguments: it just prints a blank line.

🔄 Check Your Understanding (try to answer without scrolling up)

  1. What does print("a", "b", "c", sep="-") output?
  2. What does print() do when called with no arguments?
  3. What does the end parameter control?

Verify

  1. a-b-c — the items are joined with hyphens instead of spaces.
  2. It prints a blank line (just a newline character).
  3. It controls what character(s) appear at the end of the printed output. The default is a newline (\n), which is why each print() normally starts on a new line.

2.8 input() — Listening to the User

So far, our programs just talk. They display output but don't respond to anything the user says. That changes now.

The input() function pauses the program, waits for the user to type something, and returns whatever they typed as a string.

Basic Usage

name = input("What is your name? ")
print("Hello,", name)

When you run this, the program displays What is your name? and waits. If the user types Elena and presses Enter:

What is your name? Elena
Hello, Elena

The string inside input() is the prompt — the text that tells the user what to type. Always include a trailing space in your prompt so the user's text doesn't run into the question.

Building an Interactive Program

Let's combine print() and input() to build a real interactive program. This is our first code implementation block — a program you should type out and run yourself.

💻 Code Implementation: The Greeting Program

# greeting.py — An interactive greeting program

print("=" * 35)
print("  Welcome to the Greeting Program")
print("=" * 35)
print()

name = input("What is your name? ")
city = input("What city do you live in? ")
language = input("What programming language are you learning? ")

print()
print(f"Nice to meet you, {name}!")
print(f"I hear {city} is a great place to live.")
print(f"You're going to love {language} — excellent choice!")

Walkthrough:

  • Line 1: A comment naming the file and saying what it does.
  • Lines 3-6: Print a visual banner with a horizontal rule made from = signs, followed by a blank line.
  • Lines 8-10: Three input() calls, each storing the user's response in a variable. The = sign means "store the value on the right under the name on the left" (Chapter 3 digs into exactly what that means). The variable names (name, city, language) describe what they hold — a habit you should build from day one.
  • Lines 12-15: Print personalized responses using f-strings. The {name}, {city}, and {language} placeholders get replaced with whatever the user typed.

Sample run:

===================================
  Welcome to the Greeting Program
===================================

What is your name? Elena
What city do you live in? Portland
What programming language are you learning? Python

Nice to meet you, Elena!
I hear Portland is a great place to live.
You're going to love Python — excellent choice!

🧩 Productive Struggle

Before reading on, try to modify the greeting program to ask two more questions and incorporate the answers into the output. Don't look ahead — experiment. If something doesn't work, read the error message carefully (it's trying to help you) and try again.

Spend at least 5 minutes on this before continuing. The struggle is the learning.

Everything from input() Is a String

This is crucial and will bite you eventually: input() always returns a string, even if the user types a number.

age = input("How old are you? ")
print(type(age))

If the user types 20:

How old are you? 20
<class 'str'>

The type() function tells us what kind of data we have, and it says str (string) — not int (integer). The user typed 20, but Python stored it as the text "20", not the number 20. We'll learn how to convert between types in Chapter 3.


2.9 Comments — Talking to Humans

You've already seen a few lines that start with #. Those are comments — lines that Python ignores completely. They exist solely for the humans reading the code.

# This line is ignored by Python
print("This line runs")  # This part after the # is also ignored

Output:

This line runs

Why Comments Matter

When you write code, you know exactly what it does and why. Six months from now — or when someone else reads your code — that context is gone. Comments preserve it.

Here's a simple example:

# BAD: Comment restates the code (useless)
x = 365  # set x to 365

# GOOD: Comment explains WHY
x = 365  # days in a non-leap year, used for annual calculations

The first comment is noise — you can see that x is being set to 365. The second comment adds information that isn't obvious from the code alone.

When to Comment (and When Not To)

Do comment: - Why you made a particular choice (not what the code does) - Anything that would confuse someone seeing the code for the first time - High-level descriptions of what a section of code accomplishes

Don't comment: - Every single line (this makes code harder to read, not easier) - Obvious things (x = 5 # assign 5 to x) - Instead of writing clear code (fix the code, don't explain the mess)

✅ Best Practice: Good code reads almost like English. Comments should fill in the gaps — explaining why and context, not what. As you get better at writing readable code, you'll need fewer comments.


2.10 Common First-Program Errors

You're going to make mistakes. Every programmer does. The difference between a frustrated beginner and a productive developer is how they respond to error messages. Let's build that skill now.

📊 Theme: Errors Are Not Failures, They Are Information

Every error message Python gives you contains three pieces of useful information: where the error occurred (the file and line number), what type of error it is (the error name), and why Python thinks it happened (the description). Learning to read these messages is one of the most valuable skills in this entire course.

🐛 Debugging Walkthrough: Three Common Errors

Let's intentionally break things and learn to fix them.

Error 1: SyntaxError — Python can't understand your code

print("Hello, World!)

Output:

  File "hello.py", line 1
    print("Hello, World!)
          ^
SyntaxError: unterminated string literal (detected at line 1)

(On your machine, the File line will show the full path to your file, such as C:\Users\yourname\cs1\ch02\hello.py. We've shortened it here.)

The syntax is the grammar of the programming language — the rules about how code must be structured. A syntax error means you broke one of those rules. Here, we forgot the closing quote before the parenthesis. Python points its ^ caret at the opening quote — the start of a string that never ends — and tells us the string wasn't terminated. Because syntax is checked before anything runs (remember section 2.1), none of the file runs until you fix it.

Fix: Add the missing closing quote.

print("Hello, World!")

Error 2: NameError — Python doesn't recognize a name

print(message)

Output:

Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    print(message)
          ^^^^^^^
NameError: name 'message' is not defined

A NameError means you used a name Python doesn't recognize. This usually means you either forgot to create a variable before using it, or you made a typo. Unlike the SyntaxError, this one only appears when Python actually reaches the line — which is why it comes with a Traceback (the record of what was running when it failed). The ^^^^^^^ markers underline the exact name Python choked on.

When the name is a near-miss of one Python does know, recent versions even suggest the fix. Mistyping prnt("Hi") gives:

NameError: name 'prnt' is not defined. Did you mean: 'print'?

Fix: Either define the variable first, or put quotes around it if you meant it as text:

message = "Hello, World!"
print(message)

Or, if you meant to print the word "message":

print("message")

Error 3: IndentationError — unexpected spacing

print("line one")
  print("line two")

Output:

  File "hello.py", line 2
    print("line two")
IndentationError: unexpected indent

Indentation in Python isn't just cosmetic — it's part of the language's syntax. Python uses indentation (spaces at the beginning of a line) to define code structure. We'll see why in Chapter 4 when we learn about if statements. For now, the rule is simple: don't add spaces at the beginning of a line unless Python expects them.

Fix: Remove the extra spaces:

print("line one")
print("line two")

Reading Error Messages: A Template

Python error messages for a running program follow the same structure:

Traceback (most recent call last):     ← the chain of events
  File "filename.py", line N, in ...   ← WHERE the error happened
    the offending line of code         ← WHAT code triggered it
ErrorType: description                 ← WHY Python is complaining

Syntax and indentation errors look the same minus the Traceback line, because the program never started running.

Always read the last line first — it tells you the error type and a human-readable description. Then look at the line number to find where in your code the problem is.

🔄 Check Your Understanding (try to answer without scrolling up)

  1. What's the difference between a SyntaxError and a NameError?
  2. Why does indentation matter in Python?
  3. When Python shows an error, which line should you read first?

Verify

  1. A SyntaxError means your code violates Python's grammar rules (like a missing quote or parenthesis). A NameError means you used a name that Python doesn't recognize — usually an undefined variable or a typo.
  2. Python uses indentation to define code structure (which lines belong to which blocks). Incorrect indentation breaks the grammar, so Python reports it before running anything (IndentationError is a special kind of SyntaxError).
  3. The last line — it tells you the error type and description. Then check the line number to find where in your code the problem occurred.

2.11 Project Checkpoint: TaskFlow v0.1

📐 Project Checkpoint — TaskFlow v0.1: "Hello, TaskFlow!"

Time to start building the project you'll carry through this entire course. TaskFlow v0.1 is intentionally simple — it introduces TaskFlow to the user, asks for their name, and responds with a personalized greeting. Nothing fancy. But it uses everything you learned in this chapter: print(), input(), comments, f-strings, and string repetition.

💻 Code Implementation: TaskFlow v0.1

# taskflow.py — TaskFlow v0.1
# A command-line task manager (just the greeting for now!)
# Chapter 2 project checkpoint

print("=" * 45)
print("  TaskFlow v0.1 — Your Task Manager")
print("=" * 45)
print()

# Get the user's name
name = input("What is your name? ")

# Greet the user
print()
print(f"Welcome to TaskFlow, {name}!")
print("TaskFlow helps you organize your tasks")
print("and stay on top of your work.")
print()
print("Features coming soon:")
print("  - Add and view tasks")
print("  - Set priorities")
print("  - Search and filter")
print("  - Save to file")
print()
print(f"Let's get productive, {name}!")

Walkthrough:

  • Lines 1-3: Comments describing the file. Anyone opening this file immediately knows what it is and what version.
  • Lines 5-8: A welcome banner using string repetition. The print() on line 8 adds a blank line for visual breathing room.
  • Lines 10-11: We use input() to get the user's name and store it in the variable name. The comment on line 10 is a short signpost for the section — the "high-level description" kind of comment from section 2.9.
  • Lines 13-25: Personalized output using f-strings. We give the user a preview of features we'll build in future chapters — this is a roadmap for the project.

Sample run:

=============================================
  TaskFlow v0.1 — Your Task Manager
=============================================

What is your name? Elena

Welcome to TaskFlow, Elena!
TaskFlow helps you organize your tasks
and stay on top of your work.

Features coming soon:
  - Add and view tasks
  - Set priorities
  - Search and filter
  - Save to file

Let's get productive, Elena!

🔍 Elena Connection: Elena Vasquez from Chapter 1 is the nonprofit data analyst drowning in manual work. Imagine her at this exact point in her Python journey — typing her first program, seeing her name appear on screen, and realizing: If I can make the computer respond to me, I can make it do my reports. That realization is the beginning of everything. She started right here, just like you.

Your assignment: Save this as taskflow.py in your ch02 folder. Run it. Then modify it: add one more input() call that asks what kind of tasks the user manages (homework, work, personal, etc.) and incorporate their answer into the output. There's no single right answer — just experiment.


Spaced Review: Bridge to Chapter 1

🔄 Spaced Review: Connecting to Chapter 1

In Chapter 1, you learned about the four pillars of computational thinking. Without looking back:

  1. Name all four pillars.
  2. Which pillar did you use when you broke the greeting program into "get inputs" and "display outputs"?
  3. When you used print() without knowing how it works internally, which pillar were you relying on?

Verify

  1. Decomposition, pattern recognition, abstraction, and algorithm design.
  2. Decomposition — breaking the program into smaller parts (collecting data, then displaying it).
  3. Abstraction — you used print() without needing to understand how Python converts text to pixels on screen. The internal complexity was hidden behind a simple interface.

2.12 Chapter Summary

Key Concepts

  • Python is an interpreted language — you run your source file directly, and the interpreter checks it, translates it to bytecode behind the scenes, and executes it top to bottom, with no separate compile step for you to manage. This makes it fast to develop with and perfect for learning.
  • The terminal is a text-based interface to your operating system. Commands like cd, ls/dir, and pwd let you navigate your file system.
  • The REPL (Read-Eval-Print Loop) is Python's interactive mode, perfect for experimenting with code one line at a time.
  • Scripts are .py files containing Python code. You write them in an editor and run them from the terminal.
  • print() displays output; input() collects text from the user. Together they make interactive programs.
  • Comments (#) are notes for humans that Python ignores. Use them to explain why, not what.
  • Error messages are information. Read the last line first to understand what went wrong, then check the line number to find where.

Key Terms Summary

Term Definition
Interpreter A program that runs your source code directly, with no separate compile step for you to run (Python's interpreter translates it to bytecode behind the scenes)
REPL Read-Eval-Print Loop — Python's interactive mode for testing code one expression at a time
IDE Integrated Development Environment — a code editor with built-in tools like a terminal, debugger, and code completion
Terminal A text-based interface for interacting with your operating system using typed commands
Shell The program inside the terminal that interprets your commands (e.g., bash, zsh, cmd)
Script A text file with a .py extension containing Python code that can be run as a program
Syntax The grammar rules of a programming language — how code must be structured
Syntax error An error that occurs when code violates the language's grammar rules
Indentation Spaces at the beginning of a line; Python uses indentation to define code structure
Comment A line or portion of a line starting with # that Python ignores; written for human readers
print() A built-in function that displays text and values on the screen
input() A built-in function that pauses the program, displays a prompt, and returns the user's typed response as a string

What You Should Be Able to Do

  • [ ] Install Python 3.13+ and verify the installation
  • [ ] Navigate the terminal using cd, ls/dir, and pwd
  • [ ] Use the REPL to test Python expressions interactively
  • [ ] Write a .py script and run it from the terminal
  • [ ] Use print() with sep and end parameters
  • [ ] Use input() to build interactive programs
  • [ ] Write meaningful comments
  • [ ] Read and interpret Python error messages

What's Next

In Chapter 3: Variables, Types, and Expressions, you'll learn how Python stores and manipulates data. You'll discover that Python has different types of data — integers, decimals, text, and true/false values — and that understanding these types is essential for writing programs that work correctly. You'll also encounter one of the most important threshold concepts in CS1: that variables in Python aren't boxes that hold values — they're name tags that point to objects. It's a subtle distinction, but it changes how you think about everything that follows.

You'll also build TaskFlow v0.2, which will let users add a task with a timestamp — your task manager's first real feature.


Chapter 2 Exercises → exercises.md

Chapter 2 Quiz → quiz.md

Case Study: The History of "Hello, World!" → case-study-01.md

Case Study: Setting Up a Development Environment in the Real World → case-study-02.md