Appendices A through P — installation, syntax, errors, debugging, style, functions, data structures, files, standard library, OOP, testing, projects, glossary, selected answers, and full index
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.
.exe file) and run it..pkg file).python3 --version to confirm.sudo apt update sudo apt install python3 python3 --version
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.
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, AdaTo 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.
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
| Problem | Likely Cause | Solution |
|---|---|---|
python is not recognized | Python not in PATH | Reinstall Python and check "Add Python to PATH" |
| Wrong Python version | Multiple installations | Use python3 on macOS/Linux |
| Script runs but nothing appears | Missing print() | Add print() to display output |
ModuleNotFoundError | Package not installed | Run pip install package-name |
SyntaxError on first run | Typo in code | Check for missing colons, quotes, or parentheses |
| File not found | Wrong working directory | Navigate to the correct folder first with cd |
| Indentation errors | Mixed spaces and tabs | Set your editor to use 4 spaces per indent; never tabs |
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.csvUse 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.
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)
| Type | Description | Example |
|---|---|---|
| Relative | Starts from the current directory. Portable — works regardless of where the project lives. | data/students.csv |
| Absolute | Starts from the root of the file system. Works everywhere but is tied to one machine's layout. | C:\Users\Name\projects\data.csv |
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
dir # Windows ls # macOS/Linux ls -l # Detailed listing (macOS/Linux)
python filename.py # Windows python3 filename.py # macOS/Linux python3 chapter_03/values.py # File in a subfolder
\) 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".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".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.
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.
score = 95 player_name = "Alex" is_active = True x = 10 x = x + 1 # update x a, b = 3, 7 # assign multiple values at once
# This is a single-line comment total = price + tax # inline comment at end of a line
# 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
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") # 2True 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
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: "))if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"# 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 iterationdef 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 * nnumbers = [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)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)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")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)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.
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 zeroReading this: error type is ZeroDivisionError. It happened inside divide() at line 5, which was called at line 12.
if, elif, else, for, while, def, or class. Unmatched parentheses, brackets, or quotes. Using = instead of == inside a condition.type(value). Convert where necessary with int(), float(), or str().int or float: int("hello").try/except ValueError for user input.len(sequence). Off-by-one errors in loops. Valid indexes are 0 through len(sequence) - 1.len(). Verify loop ranges carefully.key in dictionary to check before accessing. Use .get(key, default) for safe lookup.import os; print(os.getcwd()) to check the working directory.if count != 0: before dividing.None (often because a function forgot to return).return.import maths instead of import math). Module not installed.pip install package-name in the terminal.Use this checklist whenever a program is not working as expected. Work through the steps in order.
TypeError or NameError) and the message that follows.if, elif, else, for, while, def, or class must be indented by exactly 4 spaces.str, int, float, list, dict?)str to int or float?print(type(variable)) to inspect types.print() statements to display variable values at key points.>= vs >).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.
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): ...
Always use 4 spaces per indentation level. Never use tabs. Configure your code editor to automatically insert spaces when you press the Tab key.
# 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
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)# 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)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:
...my_project/
main.py
student.py
gradebook.py
report.py
data/
students.csv
tests/
test_gradebook.pyWrite 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 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() | return | |
|---|---|---|
| Makes output visible | Yes | No |
| Produces a usable value | No | Yes |
| Value can be stored | No | Yes |
| Value can be used in expressions | No | Yes |
# 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 24Use 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.
# 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.
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"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
| Need | Use |
|---|---|
| Ordered sequence, may change | List |
| Ordered sequence, should not change | Tuple |
| Unique values, fast membership testing | Set |
| Key-value pairs, lookup by name | Dictionary |
| Records (a fixed set of named fields) | Dictionary or class |
| Table (rows and columns) | List of lists |
| Collection of records | List of dictionaries |
| Grouped values by category | Dictionary of lists |
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") # 2Strings are immutable — you cannot change a character in place. You always create new strings.
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
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.
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}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)# 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"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
| Mode | Meaning |
|---|---|
"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. |
# 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")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.
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
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)| Problem | Fix |
|---|---|
| Leading/trailing spaces | value.strip() |
| Numeric fields stored as strings | int(value) or float(value) |
| Empty fields | if value: or provide a default |
| Inconsistent capitalization | value.lower() or value.title() |
| Error | Cause | Fix |
|---|---|---|
FileNotFoundError | File doesn't exist or wrong path | Check file name, extension, and current directory |
PermissionError | No read/write permission | Check file permissions |
UnicodeDecodeError | File encoding mismatch | Add encoding="utf-8" to open() |
The Python standard library is included with Python — no installation needed. This appendix introduces the modules most useful for beginners.
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
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
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)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)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"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}!")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)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
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.
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.
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.
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)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."
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) # 0students = [
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}")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.
A test case is a specific input paired with the expected output. Good test cases cover typical inputs, edge cases, and invalid inputs.
| Input | Expected | Notes |
|---|---|---|
| 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 |
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.
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()# 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)try/except where appropriate.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.
| Project | Core Skills |
|---|---|
| Personal budget tracker | Lists, dictionaries, files, CSV, functions |
| Flashcard quiz tool | Lists, dictionaries, files, randomness, loops |
| Contact book manager | Lists of dicts, files, functions, menus |
| Text file analyzer | Strings, files, counting, sorting, functions |
| Gradebook system | CSV, data aggregation, classes, file I/O |
| To-do list with persistence | Lists, files, functions, menus |
| Simple inventory manager | Dictionaries, files, classes, menus |
| Password strength checker | Strings, conditions, functions |
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.
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.
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?|ParisAlphabetical glossary of Python programming terms used throughout this textbook.
= operator.object.attribute.True and False. Used in conditions and logical operations.#. Used to explain code to human readers.+ operator.True or False. Used in if statements and loop control.if, elif, else.try/except.f. Allows expressions inside {} to be embedded directly in a string.3.14.False and never encounters a break. It runs forever unless interrupted.42.if, for, def, return, True, None.object.method().return statement return None.+, -, *, /, ==, !=, and, or, not.print() statements to display variable values and track program execution.input() that tells the user what to type.return statement.[start:stop] notation.int, float, str, bool, list, dict, tuple, set.int(), float(), or str().=.True.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.
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
total = 0 # total: 0 total = total + 5 # total: 5 total = total * 2 # total: 10 total = total - 3 # total: 7
| After Line | total |
|---|---|
total = 0 | 0 |
total = total + 5 | 5 |
total = total * 2 | 10 |
total = total - 3 | 7 |
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
int(7.9) # 7 (truncates, does not round)
int("hello") # ValueErrorscore = 73
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # CTrace: 73 is not ≥ 90 (skip). 73 is not ≥ 80 (skip). 73 is ≥ 70 (match — grade = "C"). Prints: C.
n = 1
while n <= 4:
print(n)
n += 1
# Output:
# 1
# 2
# 3
# 4Values: 2, 5, 8. Starts at 2, increments by 3, stops before 10.
pint("hello") # NameError: 'pint' is not defined
print(10 / 0) # ZeroDivisionError
[1, 2, 3][10] # IndexError
{"a": 1}["b"] # KeyError
int("abc") # ValueErrordef 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) # 13a is None because double_print has no return statement.
x = 100
def show():
x = 5
print(x)
show() # 5
print(x) # 100The x inside show() is a local variable. The global x is unchanged.
word = "Python" word[0] # 'P' word[-1] # 'n' word[2:5] # 'tho' word[:3] # 'Pyt' word[3:] # 'hon'
numbers = [10, 20, 30, 40, 50] numbers.append(60) numbers.remove(30) print(numbers) # [10, 20, 40, 50, 60] print(len(numbers)) # 5
| Task | Mode |
|---|---|
| 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" |
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()) # 30c = 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
Alphabetical index of topics, functions, keywords, syntax patterns, error types, modules, data structures, and methods — with chapter references. App. = Appendix, Ch. = Chapter.
and operator Ch. 5append() method Ch. 17, App. Hbreak statement Ch. 8class keyword Ch. 26, App. Kcontinue statement Ch. 8csv module Ch. 22, App. I, App. Jdatetime module Ch. 24, App. Jelif Ch. 6else Ch. 6, Ch. 23except clause Ch. 23FileNotFoundError App. Dfinally Ch. 23for loop Ch. 9, App. Cif statement Ch. 6, App. Cimport Ch. 15, App. CIndentationError App. DIndexError App. Dinput() Ch. 4, App. Cjson module App. JKeyError App. Dmath module Ch. 15, App. JNameError App. DNone Ch. 12, App. Nnot operator Ch. 5or operator Ch. 5os module App. Jpathlib module App. Jprint() Ch. 4, App. Crandom module Ch. 15, Ch. 24, App. Jrange() Ch. 9, App. Creturn statement Ch. 12, App. Gself Ch. 26, App. Kstatistics module App. JSyntaxError App. Dsys module App. JTypeError App. DValueError App. Dwhile loop Ch. 8, App. Cwith statement Ch. 21, App. IZeroDivisionError App. D