A try can have several except blocks — one per exception type. The block matching the raised exception runs:
def read_score(scores, position_text):
try:
position = int(position_text)
return scores[position]
except ValueError:
return "not a number"
except IndexError:
return "no such position"
scores = [80, 92, 75]
print(read_score(scores, "1"))
print(read_score(scores, "one"))
print(read_score(scores, "9"))
Output:
92
not a number
no such position
Each failure gets its own response: int("one") raised ValueError, scores[9] raised IndexError.
Catch the narrowest exception that covers the situation. A bare except: catches everything — including typos and genuine bugs — and turns them into silent wrong behavior. This course never uses it.
price_lookup with two parameters: prices (a dictionary) and item.prices[item] divided by 100 (the price is stored in cents; return dollars)."no such item". When the stored value is not divisible — a TypeError, for example the string "n/a" — return "bad price data".price_lookup({"apple": 450}, "apple") returns 4.5.
Run your code to see the output, then press Submit.
import unittest
class TestPriceLookup(unittest.TestCase):
def test_valid_item_returns_kroner(self):
self.assertEqual(price_lookup({"apple": 450}, "apple"), 4.5)
def test_missing_item(self):
self.assertEqual(price_lookup({"apple": 450}, "pear"), "no such item")
def test_unparseable_price(self):
self.assertEqual(price_lookup({"apple": "n/a"}, "apple"), "bad price data")
def price_lookup(prices, item):
try:
return prices[item] / 100
except KeyError:
return "no such item"
except TypeError:
return "bad price data"
print(price_lookup({"apple": 450}, "apple"))
print(price_lookup({"apple": 450}, "pear"))
print(price_lookup({"apple": "n/a"}, "apple"))
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.