Functions, Errors, and Files
Functions give behavior a boundary
Section titled “Functions give behavior a boundary”def normalize_name(name): cleaned = name.strip().lower() return cleaned
result = normalize_name(" Ada ")print(result)name is a parameter, the supplied string is an argument, and return sends one value back to the caller. The function’s boundary gives us a focused question: for this input, what output or failure results?
Read the last error first
Section titled “Read the last error first”Change the call to normalize_name(12). The traceback shows the chain of calls, followed by the exception type and message. Begin at the final line, then move upward to the first frame in your code. A traceback is a path to the failure, not a ceremonial wall of red text.
Catch only a failure you understand:
try: number = int("not-a-number")except ValueError as error: print("invalid integer:", error)Avoid a bare except: that turns unrelated bugs into the same vague message.
Files are external input
Section titled “Files are external input”Create numbers.txt containing one integer per line, then create:
def load_numbers(path): numbers = [] with open(path, "r", encoding="utf-8") as handle: for line_number, line in enumerate(handle, start=1): text = line.strip() if text: numbers.append(int(text)) return numbers
print(load_numbers("numbers.txt"))The with statement closes the file even when conversion fails. Add an invalid line and use the traceback to identify it. Then improve the function by catching ValueError, reporting line_number, and re-raising the error with raise.
Knowledge check
Question 1 of 2
Knowledge check complete
You answered all 2 questions correctly.
What this gives us as researchers
Section titled “What this gives us as researchers”You can isolate behavior, preserve the path to a failure, and treat file contents as untrusted input. The Python Behavior Lab combines those skills.