Skip to content
UnderDunn Courses

Functions, Errors, and Files

Programming FoundationsLesson 4 of 875 minutesLab included
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?

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.

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

Where should traceback investigation usually begin?

You can isolate behavior, preserve the path to a failure, and treat file contents as untrusted input. The Python Behavior Lab combines those skills.