Challenge 2: Line Counter — Possible Solution ==================================================================== def count_lines(filename): count = 0 with open(filename, "r") as file: for line in file: count += 1 return count print(count_lines("output.txt")) Output (using the 3-line file from Challenge 1): 3 WHY THIS WORKS AS AN ANSWER ------------------------------ with open(filename, "r") as file: reuses the chapter's own context manager pattern, guaranteeing the file closes automatically once the function is done reading it — even if something inside the loop raised an exception, tying back to the with block's guarantee from earlier in the chapter. for line in file: reuses the exact line-by-line iteration the chapter recommends specifically because it's memory-efficient — file.readlines() would load every line into a list all at once before counting, while iterating the file object directly processes one line at a time without ever holding the whole file in memory, a real advantage for very large files. count starts at 0 (outside the with block, so it survives after the block closes) and increments once per line processed — a running-total accumulator pattern reused from the loop-based accumulation covered back in Course 1, Chapter 4. Returning count only after the with block has fully finished ensures the file has been read to completion before the final number is reported.