MGU Computer Science Series — Programming with Python
Full Textbook Back Matter
Appendices A through P
Library Textbook Edition
∞
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Back Matter:
Reference, Glossary,
Answers & Index

Appendices A through P — installation, syntax, errors, debugging, style, functions, data structures, files, standard library, OOP, testing, projects, glossary, selected answers, and full index

■ 16 Appendices ■

■ Reference Edition  •  After Chapter 30 ■

This back matter supports all 30 chapters and 7 parts of Programming with Python

Appendices at a Glance

16Appendices
30Chapters Supported
7Course Parts
200+Glossary Terms
Appendix A
Installing and Running Python
Python 3 · Interpreters · Editors · Terminals · Setup Problems · Folder Organization

Installing and Running Python

Python Versions

Python has two major version families: Python 2 and Python 3. Python 2 reached its end of life in 2020 and is no longer maintained. This textbook uses Python 3 throughout. Install the most recent stable release of Python 3. Any version of Python 3.8 or later will work for all programs in this book. Check the current release at python.org.

Installing Python

Windows

  1. Go to python.org/downloads and click the button for the latest Python 3 release.
  2. Download the Windows installer (the .exe file) and run it.
  3. On the first screen, check Add Python to PATH. This step is critical — without it, your terminal will not find Python.
  4. Click Install Now and wait for the installation to complete.

macOS

  1. Go to python.org/downloads and download the macOS installer (the .pkg file).
  2. Open the file and follow the installation steps.
  3. After installation, open Terminal and type python3 --version to confirm.

Linux (Ubuntu/Debian)

Terminal
sudo apt update
sudo apt install python3
python3 --version

Checking the Installation

After installation, open a terminal and type:

python --version        # Windows
python3 --version       # macOS and Linux

You should see output like Python 3.12.0. If you see an error, Python was not installed correctly or was not added to your PATH.

Using the Interactive Shell

The Python interactive shell (REPL — Read, Evaluate, Print, Loop) lets you type expressions and see results immediately. Type python or python3 in a terminal:

>>> 2 + 3
5
>>> "hello".upper()
'HELLO'
>>> name = "Ada"
>>> print("Hello,", name)
Hello, Ada

To exit: type exit(), or press Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows). The interactive shell does not save your work — use script files for programs you want to keep.

Running Script Files

A script file is a plain text file containing Python code, ending with .py. Navigate to the file's folder first, then run it:

cd C:\Users\YourName\projects\     # Windows navigation
python hello.py                    # Windows execution

cd /home/yourname/projects/        # macOS/Linux navigation
python3 hello.py                   # macOS/Linux execution

Code Editors

Recommended for Beginners
Thonny
Free. Designed specifically for beginners. Built-in Python interpreter. Available at thonny.org.
Recommended for Beginners
VS Code
Free. Available at code.visualstudio.com. Install the Python extension after setup. Excellent for growing projects.
Bundled with Python
IDLE
Comes with Python. Simple and lightweight. Useful for early exercises without any extra installation.
For Larger Projects
PyCharm Community
Free. More powerful. Better suited once you are comfortable with the basics and working on multi-file programs.

Common Setup Problems

ProblemLikely CauseSolution
python is not recognizedPython not in PATHReinstall Python and check "Add Python to PATH"
Wrong Python versionMultiple installationsUse python3 on macOS/Linux
Script runs but nothing appearsMissing print()Add print() to display output
ModuleNotFoundErrorPackage not installedRun pip install package-name
SyntaxError on first runTypo in codeCheck for missing colons, quotes, or parentheses
File not foundWrong working directoryNavigate to the correct folder first with cd
Indentation errorsMixed spaces and tabsSet your editor to use 4 spaces per indent; never tabs

Folder Organization

Keep your programs in a consistent folder structure from day one:

python_course/
    chapter_01/
        hello.py
        practice.py
    chapter_03/
        expressions.py
        variables.py
    projects/
        unit_converter.py
        capstone/
            main.py
            data.csv
Naming Habits

Use lowercase names with underscores for all files and folders: grade_calculator.py, not Grade Calculator.py. Never use spaces in file names for programming projects. Keep each project in its own folder once programs grow beyond a single file.

Command Line and File Paths Reference

Current Directory

When you open a terminal, you are placed in a current directory. All relative file paths are interpreted from this location.

cd          # Show current directory (Windows)
pwd         # Show current directory (macOS/Linux)

Relative vs. Absolute Paths

TypeDescriptionExample
RelativeStarts from the current directory. Portable — works regardless of where the project lives.data/students.csv
AbsoluteStarts from the root of the file system. Works everywhere but is tied to one machine's layout.C:\Users\Name\projects\data.csv

Changing Folders

cd python_course          # Move into a subfolder
cd chapter_03             # Move further into a subfolder
cd ..                     # Move up one level
cd ../projects            # Move up one, then into projects
cd ~                      # Home directory (macOS/Linux)
cd C:\Users\Name\projects # Full Windows path

Listing Files

dir             # Windows
ls              # macOS/Linux
ls -l           # Detailed listing (macOS/Linux)

Running Python Files

python filename.py               # Windows
python3 filename.py              # macOS/Linux
python3 chapter_03/values.py    # File in a subfolder

Path Issues by Platform

Platform Notes
Common path gotchas for each operating system
  • WindowsUses backslashes (\) in paths. In Python strings, write Windows paths as raw strings (r"C:\path\to\file") or use forward slashes ("C:/path/to/file"), which Python accepts. Folder names with spaces must be quoted at the command line: cd "My Documents".
  • macOS/LinuxPaths are case-sensitive — Notes.txt and notes.txt are different files. The home directory is ~, which expands to /Users/yourname (macOS) or /home/yourname (Linux). Folder names with spaces must be quoted: cd "my projects".
Safe File Organization

Always know your current directory before running a script. Keep data files in the same folder as the script that reads them, or in a data/ subfolder. Use pwd or cd to confirm your location before running programs that read or write files.

Python Syntax Quick Reference

A compact reference for the Python syntax patterns introduced throughout the textbook. For a full reference, see the official Python documentation at docs.python.org.

Variables and Assignment

score = 95
player_name = "Alex"
is_active = True

x = 10
x = x + 1          # update x
a, b = 3, 7         # assign multiple values at once

Comments

# This is a single-line comment
total = price + tax   # inline comment at end of a line

Numbers

# Integers and floats
count = 42
price = 9.99

# Arithmetic operators
10 + 3      # 13    (addition)
10 - 3      # 7     (subtraction)
10 * 3      # 30    (multiplication)
10 / 3      # 3.333 (division — always returns float)
10 // 3     # 3     (floor division — discard remainder)
10 % 3      # 1     (modulo — remainder only)
10 ** 3     # 1000  (exponentiation)

# Conversion
int(3.9)    # 3   (truncates, does not round)
float(5)    # 5.0
round(3.7)  # 4

Strings

name = "Alice"
word = "Python"

len("hello")            # 5
word[0]                 # 'P'
word[-1]                # 'n'
word[0:3]               # 'Pyt'

"Hello" + " " + "World" # concatenation
"ha" * 3                # 'hahaha'

# f-strings
f"Hello, {name}! Score: {score}."

# Common methods
"hello".upper()             # 'HELLO'
"HELLO".lower()             # 'hello'
"  hello  ".strip()         # 'hello'
"hello world".split()       # ['hello', 'world']
", ".join(["a", "b", "c"])  # 'a, b, c'
"hello".replace("l", "r")   # 'herro'
"hello".find("ll")          # 2
"hello".count("l")          # 2

Booleans and Comparisons

True
False

5 == 5      # True    (equality)
5 != 3      # True    (not equal)
5 > 3       # True
5 < 3       # False
5 >= 5      # True
5 <= 4      # False

True and False   # False
True or False    # True
not True         # False

Input and Output

print("Hello, world!")
print("Score:", 95)
print(f"Name: {name}, Age: {age}")
print()                             # blank line

name = input("Enter your name: ")  # always returns str
age = int(input("Enter your age: "))
price = float(input("Enter a price: "))

Conditionals

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

Loops

# while loop
count = 0
while count < 5:
    print(count)
    count += 1

# for loop with range
for i in range(5):         # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):      # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
    print(i)

# for loop over a list
for name in names:
    print(name)

break       # exit loop immediately
continue    # skip to next iteration

Functions

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

def add(a, b):
    return a + b

result = add(3, 4)   # result is 7

def greet(name, greeting="Hello"):   # default parameter
    print(f"{greeting}, {name}!")

def square(n):
    """Return the square of n."""    # docstring
    return n * n

Lists

numbers = [1, 2, 3, 4, 5]

numbers[0]              # 1
numbers[-1]             # 5
numbers[1:4]            # [2, 3, 4]
numbers[0] = 99         # update element

numbers.append(6)
numbers.insert(0, 0)
numbers.remove(3)
numbers.pop()
numbers.sort()
numbers.reverse()
numbers.count(2)
numbers.index(4)

3 in numbers            # True or False

for n in numbers:
    print(n)

Dictionaries

student = {"name": "Alex", "grade": 90}

student["name"]                         # "Alex"
student.get("grade")                    # 90
student.get("missing", 0)               # 0 (default)
student["email"] = "[email protected]"  # add entry
student["grade"] = 95                   # update entry
del student["email"]                    # remove entry

"name" in student                       # True (key check)

for key, value in student.items():
    print(key, value)

student.keys()
student.values()
len(student)

Files

with open("notes.txt", "r") as f:
    content = f.read()

with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

with open("output.txt", "w") as f:
    f.write("Hello, file!\n")

with open("log.txt", "a") as f:
    f.write("New entry.\n")

Classes

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def is_passing(self):
        return self.grade >= 60

    def __str__(self):
        return f"{self.name} ({self.grade})"

s1 = Student("Ana", 88)
print(s1.name)          # Ana
print(s1.is_passing())  # True
print(s1)               # Ana (88)

Common Python Error Messages

When a program encounters a problem it cannot handle, Python raises an exception and prints a traceback. Understanding these messages is one of the most important debugging skills in Python.

How to Read a Traceback

Read the traceback from the bottom up. The last line gives you the error type and message. The lines above show the chain of function calls that led to the error.

Traceback (most recent call last):
  File "calculator.py", line 12, in <module>
    result = divide(10, 0)
  File "calculator.py", line 5, in divide
    return a / b
ZeroDivisionError: division by zero

Reading this: error type is ZeroDivisionError. It happened inside divide() at line 5, which was called at line 12.

Error Reference

SyntaxError
Python cannot parse the code — something is not valid Python syntax
  • Common CausesMissing colon after if, elif, else, for, while, def, or class. Unmatched parentheses, brackets, or quotes. Using = instead of == inside a condition.
  • How to FixRead the line Python points to and the line just before it. Look for missing punctuation.
IndentationError
Unexpected or missing indentation in a code block
  • Common CausesMixing spaces and tabs. Forgetting to indent after a colon. Over-indenting a line that should be at a lower level.
  • How to FixUse 4 spaces per level consistently. Configure your editor to insert spaces instead of tabs.
NameError
A variable or function name is not recognized
  • Common CausesUsing a variable before assigning a value to it. Misspelling a variable or function name. Using a variable outside its scope.
  • How to FixCheck spelling exactly. Confirm the variable was assigned before use.
TypeError
An operation is performed on the wrong type of value
  • Common CausesAdding a string and an integer without converting. Calling something that is not a function. Passing the wrong number of arguments.
  • How to FixCheck types with type(value). Convert where necessary with int(), float(), or str().
ValueError
The type is correct, but the value itself is not acceptable
  • Common CausesConverting a non-numeric string to int or float: int("hello").
  • How to FixValidate input before converting. Use try/except ValueError for user input.
IndexError
An index position does not exist in a list, string, or other sequence
  • Common CausesUsing an index equal to or greater than len(sequence). Off-by-one errors in loops. Valid indexes are 0 through len(sequence) - 1.
  • How to FixCheck the length with len(). Verify loop ranges carefully.
KeyError
A dictionary key does not exist
  • Common CausesMisspelling a key name. Assuming a key is present when it might not be.
  • How to FixUse key in dictionary to check before accessing. Use .get(key, default) for safe lookup.
FileNotFoundError
Python could not find the file at the path specified
  • Common CausesFile does not exist. Misspelled file name. Wrong current directory. Wrong path format.
  • How to FixConfirm file name and extension. Use import os; print(os.getcwd()) to check the working directory.
ZeroDivisionError
A program attempted to divide by zero
  • Common CausesDividing without checking if the divisor could be zero. User input of zero used as a denominator.
  • How to FixAdd a guard: if count != 0: before dividing.
AttributeError
An attribute or method does not exist on the object
  • Common CausesCalling a string method on an integer. Misspelling a method name. Calling a method on None (often because a function forgot to return).
  • How to FixCheck the type of the object. Confirm functions that should return a value use return.
ImportError / ModuleNotFoundError
Python could not find the module you tried to import
  • Common CausesMisspelled module name (e.g. import maths instead of import math). Module not installed.
  • How to FixCheck spelling. For third-party packages, install using pip install package-name in the terminal.

Debugging Checklist

Use this checklist whenever a program is not working as expected. Work through the steps in order.

Ten-Step Debugging Process
Work through these in order — do not skip ahead
Step 1 — Read the error message
  • Do not skip the error message. Read it completely.
  • Find the error type (such as TypeError or NameError) and the message that follows.
  • The error type tells you what went wrong; the message often names the exact value or variable.
Step 2 — Find the line number
  • The traceback includes a file name and line number. Go to that line.
  • Remember: the true cause is sometimes on an earlier line — a variable assigned the wrong value several lines before the error appeared.
Step 3 — Check spelling and names
  • Look at every variable and function name on and around the problem line.
  • Check for typos, wrong capitalization, names used before assignment, and names used outside their scope.
Step 4 — Check indentation
  • Every code block inside if, elif, else, for, while, def, or class must be indented by exactly 4 spaces.
  • Confirm your editor uses spaces, not tabs.
Step 5 — Check data types
  • What type is this variable right now? (str, int, float, list, dict?)
  • Does the operation you are performing work on this type?
  • Did you forget to convert input from str to int or float?
  • Use print(type(variable)) to inspect types.
Step 6 — Trace variable values
  • Add temporary print() statements to display variable values at key points.
  • Compare actual values to what you expected at each step.
  • Remove these debugging print statements once the bug is fixed.
Step 7 — Test one change at a time
  • Make one change and run the program. Repeat.
  • If you change several things at once, you will not know which change fixed the bug — or broke something new.
Step 8 — Use small test cases
  • Test with the simplest possible input that reproduces the problem.
  • A bug that is hard to see in a full program often becomes obvious with a tiny example.
Step 9 — Check edge cases
  • Test with zero, one element, or very large inputs.
  • Test with empty strings, empty lists, and empty files.
  • Test values at the exact boundary of any comparison (>= vs >).
  • Test negative values when the program assumes positive.
Step 10 — Explain the code out loud
  • Describe every line of the program to yourself or another person in plain language.
  • This technique — called rubber duck debugging — often reveals the difference between what the code does and what you intended it to do.

Code Style Guide

Python's community-wide style guide is called PEP 8. This appendix summarizes the most important conventions for students using this textbook. Well-styled code is easier to read, debug, test, and maintain.

Readable Names

Use lowercase with underscores (snake_case) for variables and functions. Prefer clarity over brevity. Variable names should describe what they store; function names should describe what they do.

# Unclear
x = 92
y = x * 0.9

# Clear
exam_score = 92
discounted_price = exam_score * 0.9

# Variables — noun phrases (what it is)
student_count = 30
passing_grades = []

# Functions — verb phrases (what it does)
def calculate_average(scores): ...
def find_maximum(numbers): ...

Consistent Indentation

Always use 4 spaces per indentation level. Never use tabs. Configure your code editor to automatically insert spaces when you press the Tab key.

Comments — Explain Why, Not What

# Good — explains the decision
# Multiply by 0.9 to apply a 10% discount
final_price = base_price * 0.9

# Unnecessary — restates the obvious
# Set x to 5
x = 5

Docstrings

def calculate_average(numbers):
    """Return the average of a list of numbers.

    Returns 0 if the list is empty.
    """
    if len(numbers) == 0:
        return 0
    return sum(numbers) / len(numbers)

Avoiding Repetition

# Repetitive
print(f"Student: {s1_name}, Grade: {s1_grade}")
print(f"Student: {s2_name}, Grade: {s2_grade}")

# Better — extract a function
def print_student(name, grade):
    print(f"Student: {name}, Grade: {grade}")

print_student(s1_name, s1_grade)
print_student(s2_name, s2_grade)

Small Functions and Clear Conditions

Functions should do one thing. If you cannot describe what a function does in one sentence without the word "and," it probably does too much. For conditions, avoid double negatives and unnecessary comparisons with True or False:

# Unnecessary
if is_active == True:
    ...

# Better
if is_active:
    ...

Project Organization

my_project/
    main.py
    student.py
    gradebook.py
    report.py
    data/
        students.csv
    tests/
        test_gradebook.py

Function Design Reference

When to Write a Function

Write a function when you need to do the same task in more than one place; when a block of code has a clear, nameable purpose; when a section has grown long enough to benefit from a name; or when you want to test a piece of logic separately. Do not write functions just to divide code into pieces without reason.

Parameters and Arguments

Parameters are the variable names in a function definition. Arguments are the actual values passed when calling the function.

def greet(name, greeting):   # name, greeting = parameters
    print(f"{greeting}, {name}!")

greet("Alice", "Hello")      # "Alice", "Hello" = arguments

Print Versus Return

print()return
Makes output visibleYesNo
Produces a usable valueNoYes
Value can be storedNoYes
Value can be used in expressionsNoYes
# Printing inside — result cannot be reused
def add_and_print(a, b):
    print(a + b)

x = add_and_print(3, 4)   # prints 7, but x is None

# Returning — result can be reused
def add(a, b):
    return a + b

x = add(3, 4)         # x is 7
y = add(x, 10)        # y is 17
print(x + y)          # prints 24
The Core Rule

Use return for functions that compute or produce values. Use print() only when you explicitly want to display something to the user. A function that prints its result cannot be composed with other functions.

Local Variables and Avoiding Globals

# Fragile — depends on global state
total = 0
def add_to_total(n):
    global total
    total += n

# Better — explicit and testable
def add(current_total, n):
    return current_total + n

total = add(total, 5)

Globals are acceptable for program-wide constants that never change: MAX_SCORE = 100. For everything else, pass values as arguments and return results.

Helper Functions

def is_valid_score(score):
    """Return True if score is between 0 and 100."""
    return 0 <= score <= 100

def letter_grade(score):
    """Return the letter grade for a score."""
    if not is_valid_score(score):
        return "Invalid"
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

Testing Functions

print(letter_grade(95))    # A
print(letter_grade(83))    # B
print(letter_grade(60))    # D
print(letter_grade(59))    # F
print(letter_grade(-5))    # Invalid
print(letter_grade(105))   # Invalid

Data Structure Reference

Choosing a Data Structure

NeedUse
Ordered sequence, may changeList
Ordered sequence, should not changeTuple
Unique values, fast membership testingSet
Key-value pairs, lookup by nameDictionary
Records (a fixed set of named fields)Dictionary or class
Table (rows and columns)List of lists
Collection of recordsList of dictionaries
Grouped values by categoryDictionary of lists

Strings

s = "hello"
len(s)                  # 5
s[0]                    # 'h'
s[-1]                   # 'o'
s[1:4]                  # 'ell'
s.upper()               # 'HELLO'
s.strip()               # removes whitespace
s.split(",")            # splits on delimiter
", ".join(["a","b"])    # joins list
s.replace("l","r")      # 'herro'
s.find("ll")            # 2
s.count("l")            # 2

Strings are immutable — you cannot change a character in place. You always create new strings.

Lists

lst = [10, 20, 30, 40, 50]
lst[0]                  # 10
lst[-1]                 # 50
lst[1:4]                # [20, 30, 40]
lst[0] = 99             # update in place
lst.append(60)
lst.insert(0, 5)
lst.remove(30)
lst.pop()
lst.sort()
lst.reverse()
lst.count(10)
lst.index(20)
20 in lst               # True

Tuples

point = (3, 7)
point[0]                # 3
len(point)              # 2
x, y = point            # unpacking
single = (42,)          # trailing comma required for single element

Use tuples when the collection should not change: coordinates, RGB values, bundled function results.

Sets

colors = {"red", "blue", "green"}
empty = set()           # NOT {} — that creates an empty dict

colors.add("yellow")
colors.remove("red")
colors.discard("pink")  # no error if not present

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b                   # union: {1, 2, 3, 4, 5, 6}
a & b                   # intersection: {3, 4}
a - b                   # difference: {1, 2}

Dictionaries

person = {"name": "Sam", "age": 25}
person["name"]                      # "Sam"
person.get("phone", "Unknown")      # safe lookup
person["email"] = "[email protected]"    # add
person["age"] = 26                  # update
del person["age"]                   # remove

"name" in person                    # True

for key, value in person.items():
    print(key, "->", value)

Nested Structures

# List of dictionaries (collection of records)
students = [
    {"name": "Ana", "grade": 91},
    {"name": "Ben", "grade": 78}
]
students[0]["name"]     # "Ana"
for s in students:
    print(s["name"], s["grade"])

# Dictionary of lists (grouped values)
schedule = {
    "Monday":    ["Math", "Science"],
    "Tuesday":   ["English", "History"]
}
schedule["Monday"][0]   # "Math"

Common Methods Summary

String: upper, lower, strip, split, join, replace, find, count, startswith, endswith, isdigit, isalpha

List: append, insert, remove, pop, sort, reverse, count, index, extend, clear

Dictionary: get, keys, values, items, pop, update, setdefault, clear

Set: add, remove, discard, union, intersection, difference, issubset, issuperset

File and CSV Reference

File Modes

ModeMeaning
"r"Read. Error if file does not exist. (Default)
"w"Write. Creates file if it doesn't exist. Overwrites if it does.
"a"Append. Creates file if needed. Adds to end without erasing existing content.
"x"Create. Error if file already exists.

Reading, Writing, and Appending

# Read entire file
with open("notes.txt", "r") as f:
    content = f.read()

# Read one line at a time
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

# Read all lines into a list
with open("notes.txt", "r") as f:
    lines = f.readlines()

# Write (creates or overwrites)
with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")

# Append to end
with open("log.txt", "a") as f:
    f.write("New entry.\n")
Always Use with

The with statement automatically closes the file when the block ends — even if an error occurs. This prevents file corruption and resource leaks. Always use with open(...) as f: instead of calling f.close() manually.

CSV Structure

A CSV file stores table data as plain text. Each row is one line; columns are separated by commas. The first row is usually a header row.

name,score,grade
Ana,91,A
Ben,78,C
Cal,85,B

Reading and Writing CSV

import csv

# Read with csv.reader (rows as lists)
with open("students.csv", "r", newline="") as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        print(row)

# Read with csv.DictReader (rows as dictionaries)
with open("students.csv", "r", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["score"])

# Write with csv.writer
with open("results.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "score", "grade"])
    writer.writerow(["Ana", 91, "A"])

# Write with csv.DictWriter
students = [{"name": "Ana", "score": 91}]
with open("results.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score"])
    writer.writeheader()
    for row in students:
        writer.writerow(row)

Cleaning Table Data

ProblemFix
Leading/trailing spacesvalue.strip()
Numeric fields stored as stringsint(value) or float(value)
Empty fieldsif value: or provide a default
Inconsistent capitalizationvalue.lower() or value.title()

Common File Errors

ErrorCauseFix
FileNotFoundErrorFile doesn't exist or wrong pathCheck file name, extension, and current directory
PermissionErrorNo read/write permissionCheck file permissions
UnicodeDecodeErrorFile encoding mismatchAdd encoding="utf-8" to open()

Standard Library Beginner Map

The Python standard library is included with Python — no installation needed. This appendix introduces the modules most useful for beginners.

math

import math

math.sqrt(16)           # 4.0
math.floor(3.9)         # 3
math.ceil(3.1)          # 4
math.pi                 # 3.14159...
math.e                  # 2.71828...
math.log(100, 10)       # 2.0
math.pow(2, 10)         # 1024.0
math.factorial(5)       # 120
math.gcd(12, 8)         # 4

random

import random

random.random()                  # float in [0.0, 1.0)
random.randint(1, 10)            # integer in [1, 10] inclusive
random.uniform(1.0, 5.0)        # float in [1.0, 5.0]
random.choice(["a", "b", "c"])  # random item from list
random.shuffle(my_list)          # shuffle in place
random.sample(my_list, 3)       # 3 unique random items
random.seed(42)                  # set seed for reproducibility

datetime

from datetime import date, datetime, timedelta

today = date.today()
now = datetime.now()

today.strftime("%B %d, %Y")        # "November 15, 2024"
now.strftime("%H:%M")              # "14:32"
datetime.strptime("2024-01-01", "%Y-%m-%d")

yesterday = today - timedelta(days=1)
two_weeks = today + timedelta(weeks=2)

pathlib

from pathlib import Path

p = Path("data/students.csv")
p.exists()          # True if file exists
p.name              # "students.csv"
p.stem              # "students"
p.suffix            # ".csv"
p.parent            # Path("data")

p.read_text()
p.write_text("content")

for f in Path("data").glob("*.txt"):
    print(f)

os (Introductory)

import os

os.getcwd()                          # current working directory
os.listdir(".")                      # files in current directory
os.path.exists("data.txt")           # True if path exists
os.path.join("data", "file.txt")     # "data/file.txt"
os.path.basename("/a/b/c.txt")       # "c.txt"

sys (Introductory)

import sys

sys.argv            # command-line arguments list
sys.exit()          # terminate the program
sys.exit(1)         # terminate with error code

# Example: python greet.py Alice
if len(sys.argv) < 2:
    print("Usage: python greet.py <name>")
    sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!")

json (Introductory)

import json

data = {"name": "Ana", "score": 91}
json_string = json.dumps(data)         # to string
parsed = json.loads(json_string)       # from string
parsed["name"]                         # "Ana"

with open("data.json", "w") as f:      # write to file
    json.dump(data, f, indent=4)

with open("data.json", "r") as f:      # read from file
    loaded = json.load(f)

statistics (Introductory)

import statistics

scores = [78, 85, 91, 63, 88]

statistics.mean(scores)     # average
statistics.median(scores)   # middle value
statistics.mode(scores)     # most common value
statistics.stdev(scores)    # sample standard deviation

How to Read Documentation

The official Python documentation at docs.python.org is the authoritative reference. When reading documentation for a function, look for: the signature (name, parameters, defaults), the description, parameter types, return value and type, examples, and notes on edge cases.

Practical Approach

When exploring a new module: read the overview paragraph, find functions relevant to your task, read their signatures and descriptions, try a small example in the interactive shell, and test edge cases before using the function in a larger program.

Object-Oriented Programming Reference

Classes, Objects, and Instances

A class is a template for creating objects. An object is a specific instance of a class — each with its own data. Instance and object mean the same thing in Python. Class names use CapWords (PascalCase): BankAccount, StudentRecord.

Attributes, Methods, self, and __init__

class Student:
    def __init__(self, name, grade):  # initializer
        self.name = name              # instance attribute
        self.grade = grade

    def is_passing(self):             # method
        return self.grade >= 60

    def apply_bonus(self, points):
        self.grade += points

    def __str__(self):                # string representation
        return f"{self.name} ({self.grade})"

s = Student("Ben", 55)
print(s.is_passing())    # False
s.apply_bonus(10)
print(s.grade)           # 65
print(s.is_passing())    # True
print(s)                 # Ben (65)
Understanding self

self refers to the specific object on which a method is being called. It is always the first parameter of every method definition, but you do not pass it explicitly — Python passes it automatically. Inside the method, self.name means "the name attribute of this particular object."

Object State

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

    def reset(self):
        self.count = 0

c = Counter()
c.increment()
c.increment()
print(c.count)     # 2
c.reset()
print(c.count)     # 0

Lists of Objects

students = [
    Student("Ana", 91),
    Student("Ben", 78),
    Student("Cal", 55)
]

for s in students:
    status = "passing" if s.is_passing() else "failing"
    print(f"{s.name}: {status}")

When to Use Classes

Classes are useful when you need to create multiple items of the same kind, each with its own state; when data and operations on it naturally belong together; or when you find yourself grouping related data in a dictionary and writing functions to operate on it — a class bundles these together more cleanly. Do not create a class just to have one. A simple function or dictionary is often the right choice for simple tasks.

Testing and Refactoring Reference

Test Cases

A test case is a specific input paired with the expected output. Good test cases cover typical inputs, edge cases, and invalid inputs.

InputExpectedNotes
95"A"Typical A range
90"A"Exact boundary
89"B"Just below A
60"D"Exact D boundary
59"F"Just below passing
0"F"Minimum score
-1"Invalid"Below valid range
101"Invalid"Above valid range

Assertions

def add(a, b):
    return a + b

assert add(2, 3) == 5
assert add(0, 0) == 0
assert add(-1, 1) == 0

print("All tests passed.")

If any assertion fails, Python stops immediately with AssertionError. Assertions are a lightweight way to catch mistakes before programs grow larger.

Unit Tests with unittest

import unittest

def multiply(a, b):
    return a * b

class TestMultiply(unittest.TestCase):

    def test_positive(self):
        self.assertEqual(multiply(3, 4), 12)

    def test_zero(self):
        self.assertEqual(multiply(0, 5), 0)

    def test_negative(self):
        self.assertEqual(multiply(-2, 3), -6)

if __name__ == "__main__":
    unittest.main()

Refactoring — Removing Duplication

# Before — duplicated logic
if score1 >= 90: print(f"{name1}: A")
elif score1 >= 80: print(f"{name1}: B")
else: print(f"{name1}: F")

if score2 >= 90: print(f"{name2}: A")
elif score2 >= 80: print(f"{name2}: B")
else: print(f"{name2}: F")

# After — extracted function
def print_grade(name, score):
    if score >= 90: print(f"{name}: A")
    elif score >= 80: print(f"{name}: B")
    else: print(f"{name}: F")

print_grade(name1, score1)
print_grade(name2, score2)
Code Review Checklist
Use when reviewing your own code or a classmate's code
Names and Structure
  • Every variable has a clear, descriptive name.
  • Every function does one thing.
  • Every function has a docstring.
  • There is no repeated code that could be a function.
Logic and Safety
  • All conditions are easy to read and understand.
  • There are test cases for typical inputs, edge cases, and invalid inputs.
  • Error cases are handled with try/except where appropriate.
Tidiness
  • Debugging print statements have been removed.
  • Indentation is consistent throughout.
  • Someone unfamiliar with the program could understand it after reading it.

Capstone Project Guide

Choosing a Project

A good capstone project solves a real, specific problem; fits within one or a few Python files; uses multiple skills from the course; and is scoped appropriately — completable in the time available, but substantial enough to demonstrate real programming.

ProjectCore Skills
Personal budget trackerLists, dictionaries, files, CSV, functions
Flashcard quiz toolLists, dictionaries, files, randomness, loops
Contact book managerLists of dicts, files, functions, menus
Text file analyzerStrings, files, counting, sorting, functions
Gradebook systemCSV, data aggregation, classes, file I/O
To-do list with persistenceLists, files, functions, menus
Simple inventory managerDictionaries, files, classes, menus
Password strength checkerStrings, conditions, functions

Writing Requirements

Before writing code, write down what the program should do in plain language. Requirements answer: what does the user need this program to do? Requirements should be specific enough that you can describe success and failure clearly. If a requirement cannot be tested, it is too vague.

Planning Milestones

Break the project into milestones — smaller pieces of working functionality built one at a time. Each milestone should produce a working, if incomplete, program. Never try to build everything at once.

Example Milestones
Flashcard quiz tool — seven milestones from first working version to complete
  • Milestone 1Read the question file and print questions to the screen.
  • Milestone 2Ask the user one question and check the answer.
  • Milestone 3Loop through all questions and track a score.
  • Milestone 4Shuffle questions randomly before each session.
  • Milestone 5Display the score at the end.
  • Milestone 6Handle file errors and empty input gracefully.
  • Milestone 7Clean up code, add docstrings, test edge cases.

Documentation

README Format
Program: Flashcard Quiz Tool
Author: Student Name
Date: November 2024

Description:
    Reads questions from a text file and quizzes the user.
    Tracks the score and reports results at the end.

How to run:
    python flashcard.py questions.txt

File format (questions.txt):
    One question per line, question and answer separated by |
    Example:
    What is 7 * 8?|56
    Capital of France?|Paris
Capstone Checklist
Confirm each point before presenting your project
Requirements and Design
  • Written requirements describe what the program does clearly enough to test.
  • Data structures are designed before coding begins.
  • Milestones are planned and completed in order.
Implementation and Testing
  • Every function works correctly on typical inputs.
  • Edge cases (empty input, zero, missing files) are handled.
  • All test cases pass; results are documented.
Documentation and Presentation
  • Every function has a docstring.
  • A README explains how to run the program and what files it needs.
  • The program runs cleanly from start to finish in a demonstration.
  • A written reflection is complete.

Glossary

Alphabetical glossary of Python programming terms used throughout this textbook.

Selected Answers

Representative answers for tracing, output prediction, type conversion, error classification, and OOP exercises from Parts I through VI. Open-ended programming tasks have multiple valid solutions; representative approaches are shown where applicable.

Part I — Getting Started with Python
Chapters 1 – 4
Chapter 3 — Predict the Output
Arithmetic expressions and operator precedence
x = 10
y = 3
print(x + y)    # 13
print(x * y)    # 30
print(x / y)    # 3.3333333333333335
print(x // y)   # 3
print(x % y)    # 1
Chapter 3 — Variable Tracing
Trace the value of total after each line
total = 0           # total: 0
total = total + 5   # total: 5
total = total * 2   # total: 10
total = total - 3   # total: 7
After Linetotal
total = 00
total = total + 55
total = total * 210
total = total - 37
Chapter 4 — Type Conversion Practice
What does each expression evaluate to?
int("42")       # 42
float("3.14")   # 3.14
str(100)        # "100"
int(7.9)        # 7   (truncates, does not round)
int("hello")    # ValueError
Part II — Control Flow and Program Logic
Chapters 5 – 10
Chapter 6 — Code Tracing
Which branch runs? What is printed?
score = 73
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)    # C

Trace: 73 is not ≥ 90 (skip). 73 is not ≥ 80 (skip). 73 is ≥ 70 (match — grade = "C"). Prints: C.

Chapter 8 — While Loop Tracing
What does this loop print?
n = 1
while n <= 4:
    print(n)
    n += 1

# Output:
# 1
# 2
# 3
# 4
Chapter 9 — Range Practice
What values does range(2, 10, 3) produce?

Values: 2, 5, 8. Starts at 2, increments by 3, stops before 10.

Chapter 10 — Error Classification
What exception does each line raise?
pint("hello")         # NameError: 'pint' is not defined
print(10 / 0)         # ZeroDivisionError
[1, 2, 3][10]         # IndexError
{"a": 1}["b"]         # KeyError
int("abc")            # ValueError
Part III — Functions and Program Design
Chapters 11 – 15
Chapter 12 — Print vs. Return
What is the value of a? What does b hold?
def double_print(n):
    print(n * 2)

def double_return(n):
    return n * 2

a = double_print(5)   # prints 10; a is None
b = double_return(5)  # b is 10; nothing is printed
print(b + 3)          # 13

a is None because double_print has no return statement.

Chapter 13 — Scope Tracing
What is printed? Is the global x affected?
x = 100

def show():
    x = 5
    print(x)

show()      # 5
print(x)    # 100

The x inside show() is a local variable. The global x is unchanged.

Parts IV – VI — Data Structures, Files, and OOP
Chapters 16 – 29
Chapter 16 — String Indexing
What does each expression produce?
word = "Python"
word[0]     # 'P'
word[-1]    # 'n'
word[2:5]   # 'tho'
word[:3]    # 'Pyt'
word[3:]    # 'hon'
Chapter 17 — List Tracing
What is the list after these operations?
numbers = [10, 20, 30, 40, 50]
numbers.append(60)
numbers.remove(30)
print(numbers)      # [10, 20, 40, 50, 60]
print(len(numbers)) # 5
Chapter 21 — File Mode Selection
Which mode should you use for each task?
TaskMode
Read an existing file"r"
Create a new file and write to it"w"
Add lines to an existing log file"a"
Create a file; fail if it exists"x"
Chapter 26 — Object Tracing
What does this output?
class Box:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

b = Box(4, 6)
print(b.area())   # 24
b.width = 5
print(b.area())   # 30
Chapter 27 — State Tracing
What is count after each step?
c = Counter()       # count: 0
c.increment()       # count: 1
c.increment()       # count: 2
c.increment()       # count: 3
print(c.count)      # 3
c.reset()
print(c.count)      # 0

Index

Alphabetical index of topics, functions, keywords, syntax patterns, error types, modules, data structures, and methods — with chapter references. App. = Appendix, Ch. = Chapter.

A
  • and operator Ch. 5
  • append mode (files) Ch. 21, App. I
  • append() method Ch. 17, App. H
  • argument Ch. 12, App. G, App. N
  • arithmetic operators Ch. 3, App. C
  • assertion Ch. 29, App. L
  • assignment Ch. 3, App. C, App. N
  • attribute Ch. 26, Ch. 27, App. K, App. N
  • automation Ch. 25
  • absolute path Ch. 2, Ch. 21, App. B
B
  • break statement Ch. 8
  • Boolean Ch. 3, Ch. 5, App. C, App. N
  • Boolean operators Ch. 5
  • bug App. E, App. N
C
  • class keyword Ch. 26, App. K
  • class definition Ch. 26
  • code block Ch. 6, Ch. 11
  • code editor Ch. 2, App. A
  • code style App. F
  • command line Ch. 2, App. B
  • comment Ch. 4, App. C, App. F
  • comparison operators Ch. 5
  • conditional Ch. 6, App. C
  • continue statement Ch. 8
  • csv module Ch. 22, App. I, App. J
  • CSV file Ch. 22, App. I
  • current directory Ch. 2, App. B
D
  • data structure App. H
  • datetime module Ch. 24, App. J
  • debugging Ch. 10, Ch. 29, App. D, App. E
  • decomposition Ch. 14
  • default parameter Ch. 12, App. G
  • dictionary Ch. 18, Ch. 19, App. C, App. H
  • docstring Ch. 29, App. F, App. G
E
  • edge case Ch. 10, App. L
  • elif Ch. 6
  • else Ch. 6, Ch. 23
  • exception Ch. 23, App. D
  • except clause Ch. 23
  • expression Ch. 3, App. C, App. N
F
  • f-string Ch. 4, App. C, App. N
  • file Ch. 21, App. I
  • file path Ch. 2, Ch. 21, App. B
  • FileNotFoundError App. D
  • finally Ch. 23
  • float Ch. 3, App. C, App. N
  • for loop Ch. 9, App. C
  • function Ch. 11 – 14, App. C, App. G
G
  • global variable Ch. 13, App. G
  • glossary App. N
H – I
  • helper function Ch. 14, App. G
  • IDLE App. A
  • if statement Ch. 6, App. C
  • immutable App. H, App. N
  • import Ch. 15, App. C
  • IndentationError App. D
  • index Ch. 16, Ch. 17, App. H
  • IndexError App. D
  • infinite loop Ch. 8, App. N
  • input() Ch. 4, App. C
  • instance Ch. 26, App. K, App. N
  • integer Ch. 3, App. C, App. N
  • iteration Ch. 7, App. N
J – L
  • json module App. J
  • KeyError App. D
  • library App. J, App. N
  • list Ch. 17, Ch. 19, App. C, App. H
  • list of dictionaries Ch. 19, App. H
  • local variable Ch. 13, App. G, App. N
  • logical operators Ch. 5
  • loop Ch. 7, Ch. 8, Ch. 9, App. C
M – N
  • math module Ch. 15, App. J
  • method Ch. 16 – 18, Ch. 26, Ch. 27, App. K
  • module Ch. 15, App. C, App. J
  • mutable App. H, App. N
  • NameError App. D
  • namespace Ch. 15, App. N
  • nested data structures Ch. 19
  • None Ch. 12, App. N
  • not operator Ch. 5
O – Q
  • object Ch. 26, Ch. 27, App. K, App. N
  • object state Ch. 27, App. K
  • or operator Ch. 5
  • os module App. J
  • parameter Ch. 12, App. G, App. N
  • pathlib module App. J
  • path (file system) Ch. 2, Ch. 21, App. B
  • print-style debugging Ch. 10, App. E
  • print() Ch. 4, App. C
  • print vs. return Ch. 12, App. G
  • prompt Ch. 4, App. N
R – S
  • random module Ch. 15, Ch. 24, App. J
  • range() Ch. 9, App. C
  • refactoring Ch. 14, Ch. 29, App. L
  • relative path Ch. 2, Ch. 21, App. B
  • return statement Ch. 12, App. G
  • scope Ch. 13, App. N
  • self Ch. 26, App. K
  • sentinel value Ch. 8
  • set Ch. 18, App. H
  • slicing Ch. 16, Ch. 17, App. H
  • standard library Ch. 15, App. J
  • state Ch. 13, Ch. 27, App. K
  • statistics module App. J
  • string Ch. 3, Ch. 16, App. C, App. H
  • SyntaxError App. D
  • sys module App. J
T – Z
  • terminal Ch. 2, App. A, App. B
  • test case Ch. 10, App. L
  • traceback Ch. 10, Ch. 23, App. D
  • tracing (code) Ch. 3, Ch. 7, Ch. 10, App. E
  • tuple Ch. 18, App. H, App. N
  • TypeError App. D
  • type conversion Ch. 4, App. C
  • unit test Ch. 29, App. L
  • ValueError App. D
  • variable Ch. 3, App. C, App. N
  • while loop Ch. 8, App. C
  • with statement Ch. 21, App. I
  • ZeroDivisionError App. D
MGU Library Connection
  • Programming with Python — Chapters 1 – 30 (main text)
  • Companion: Python Syntax Quick Reference Card
  • Companion: Common Python Errors Poster
  • Companion: Debugging Checklist Worksheet
  • Companion: Data Structure Selection Guide
  • Companion: Function Design Reference Card
  • Companion: Capstone Project Rubric and Checklist
  • Next course: Data Structures and Algorithms (builds on this textbook)
  • Next course: Python for Data Science (requires this textbook)