Reading Tracebacks

Reading Tracebacks

When Python hits an error it stops and prints a traceback — a report of what went wrong and where:

def average(numbers):
    return total / len(numbers)

print(average([4, 8]))

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(average([4, 8]))
  File "main.py", line 2, in average
    return total / len(numbers)
NameError: name 'total' is not defined

Read it from the bottom up:

  • The last line names the error and describes it: a NameError, because total was never created.
  • The lines above it show where: line 2, inside average.
  • Above that, the chain of calls that got there: line 4 called average.

Error types you have met so far: NameError (a name that does not exist — often a typo), TypeError (an operation on the wrong type, like "a" + 1), IndexError (a list index that does not exist), KeyError (a missing dictionary key), and SyntaxError (Python could not read the code at all — reported before anything runs).

A traceback is information, not a verdict. The bottom line tells you what kind of mistake; the line number tells you where to look.

Exercise

The starter code defines total_price, but running it raises an error.

  1. Press Run and read the traceback, bottom line first.
  2. Find the line it points to and fix the mistake.
  3. Run again — the output should be 36.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestTotalPrice(unittest.TestCase):
    def test_three_prices(self):
        self.assertEqual(total_price([12, 20, 4]), 36)

    def test_empty_list_totals_zero(self):
        self.assertEqual(total_price([]), 0)

    def test_single_price(self):
        self.assertEqual(total_price([7]), 7)
def total_price(prices):
    total = 0
    for price in prices:
        total += price
    return total


print(total_price([12, 20, 4]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.