Home | Lecture 3 | Problem 3.1 | Problem 3.2 | Problem 3.3 | Problem 3.4
Suppose that you’re in the habit of making a list of items you need from the grocery store.
In a file called grocery.py, implement a program that prompts the user for items, one per line, until the user inputs control-d (which is a common way of ending one’s input to a program). Then output the user’s grocery list in all uppercase, sorted alphabetically by item, prefixing each line with the number of times the user inputted that item. No need to pluralize the items. Treat the user’s input case-insensitively.
Hints
-
Note that you can detect when the user has inputted control-d by catching an
[EOFError](https://docs.python.org/3/library/exceptions.html#EOFError)with code like:try: item = input() except EOFError: ...
-
Odds are you’ll want to store your grocery list as a
dict. -
Note that a
dictcomes with quite a few methods, per docs.python.org/3/library/stdtypes.html#mapping-types-dict, among themget, and supports operations like:d[key]
and
if key in d:
...wherein d is a dict and key is a str.
Be sure to avoid or catch any [KeyError](https://docs.python.org/3/library/exceptions.html#KeyError).
From the root of your repository execute cd 3-Exceptions So your current working directory is ...
/3-Exceptions $:Next execute
mkdir groceryto make a folder called grocery in your codespace.
Then execute
cd groceryto change directories into that folder. You should now see your terminal prompt as /3-Exceptions/grocery $. You can now execute
code grocery.pyto make a file called grocery.py where you’ll write your program.
Here’s how to test your code manually:
-
Run your program with
python grocery.py. Typemangoand press Enter, then typestrawberryand press Enter, followed by control-d. Your program should output:1 MANGO 1 STRAWBERRY
-
Run your program with
python grocery.py. Typemilkand press Enter, then typemilkagain and press Enter, followed by control-d. Your program should output:2 MILK
-
Run your program with
python grocery.py. Typetortillaand press Enter, then typesweet potatoand press Enter, followed by control-d. Your program should output:1 SWEET POTATO 1 TORTILLA
At the /3-Exceptions/grocery $ prompt in your terminal:
git add -A Add all changed files in the repository to be committed
git commit -m “Upload completed grocery.py“Commit all changes in the REPO with the comment “Upload completed grocery.py“ note: If the file is not complete, adjust the comment to describes what is being commited
git push Push all changes to the REPO