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:
NameError, because total was never created.average.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.
The starter code defines total_price, but running it raises an error.
36.Run your code to see the output, then press Submit.
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]))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.