Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click
this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Level 08: files and exceptions
0/9 0 of 9 activities solved
1. Saving data
Not yet solved
2. School club
Not yet solved
3. Shopping list
Not yet solved
4. Attributes
Not yet solved
5. Cookies
Not yet solved
6. Morse code
Not yet solved
7. ini file
Not yet solved
8. Amino acids
Not yet solved
9. Gamertag
Not yet solved
Next series
Level 09: two-dimension arrays and lists
Previous activity
2. School club
Next activity
4. Attributes
Sign in to hand in your solution and get feedback.
# Shopping list program
# -------------------------
# Subprograms
# -------------------------
def add_item():
new_item = input("Enter the item to add to the list: ")
file = open("shopping.txt", "a")
new_item = new_item + "\n"
file.write(new_item)
file.close()
def output_items():
try:
file = open("shopping.txt", "r")
except FileNotFoundError:
file = open("shopping.txt", "w")
file.close()
else:
print("-----------------------------")
for item in file:
item = item.strip()
print(item)
file.close()
print("-----------------------------")
def sort_items():
try:
file = open("shopping.txt", "r")
except FileNotFoundError:
file = open("shopping.txt", "w")
file.close()
else:
item_list = []
for item in file:
item = item.strip()
item_list.append(item)
file.close()
item_list.sort()
file = open("shopping.txt", "w")
for item in item_list:
item = item + "\n"
file.write(item)
file.close()
def menu():
choice = ""
while choice != "4":
print("1. Add item")
print("2. Output shopping list")
print("3. Sort list")
print("4. Quit")
while choice not in ["1", "2", "3", "4"]:
choice = input("Enter choice: ")
match choice:
case "1":
add_item()
choice = ""
case "2":
output_items()
choice = ""
case "3":
sort_items()
choice = ""
# -------------------------
# Main program
# -------------------------
menu()
Feedback