livepython.net

151. Fix a KeyError in a Price Lookup

MediumExceptions

Overview

A KeyError means the key isn't in the dictionary. Check before you look it up.

Problem Statement

A tea stall sells tea for 20, coffee for 30 and samosa for 15. The program reads an item and prints its price, like this for tea:

tea costs 20

But for an item that isn't on the menu, like cake, it crashes with KeyError: 'cake'. Fix it, so that it prints this instead:

Sorry, we don't sell cake

Item names are exact: Tea with a capital T is not on the menu.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Input

One item name. Example:

cake

Output

The output for that example:

Sorry, we don't sell cake

The tests try 4 different inputs.

Learn this firstChapter 17 · Python Exceptions: Read Errors and Know Their Types
solution.py
prices = {"tea": 20, "coffee": 30, "samosa": 15}
item = input()
print(f"{item} costs {prices[item]}")

EXPECTED OUTPUT

1tea costs 20

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.