About the challenges
The challenges below allow you to apply your knowledge of the topics up to this point.
Challenge 1: Shopping list 2
Add to the shopping list program you created earlier. When the program first loads it should read in the exisitng shopping list. When the user opts to close the program it shold save the current contents of the list
to the text file. It is initially set up to use the eval method but if you prefer you can change it to line by line.
def add_item(shop_list): item = input("Enter an item to add to the shopping list: ").title() shop_list.append(item)
return shop_list
def view_list(shop_list): print("Shopping list") for item in list:
print(item)
def remove_item(shop_list): view_list(shop_list)
choice = input("Which item do you want to remove") shop_list.remove(choice) return shop_list
def empty_list(shop_list):
shop_list.clear() return shop_list
file = open("shopping.txt") shopping_list = eval(file.read()) file.close()
choice = 0 while choice != 5: choice = int(input("Choose 1. Add item 2. View items 3. Remove item 4. Clear list or 5. End program"))
if choice == 1: shopping_list = add_item(shopping_list) elif choice == 2:
view_list(shopping_list) elif choice == 3: shopping_list = remove_item(shopping_list)
elif choice == 4: shopping_list = empty_list(shopping_list) elif choice == 5:
print("Thanks for using the shopping list program") file = open("shopping.txt","w")
file.write(str(shopping_list)) file.close() |
Challenge 2: Savings monitor 2
Update the savings monitor program so that it stores the amount of savings in a textfile. The current balance should be read in when the program opens and written to the text file when the program closes.
def deposit(savings): amount = float(input("Enter amount to be saved: ")) savings = savings + amount return savings
def withdraw(savings):
amount = float(input("Enter amount to be withdrawn: ")) savings = savings - amount return savings
def view(savings):
print(f"Current savings:{savings}")
file = open("savings.txt") savings = float(file.read()) file.close()
choice = 0 while choice != 4: choice = int(input("Choose 1. Add savings 2. Withdraw savings 3. View savings 4. Close program")) if choice == 1:
savings = deposit(savings) elif choice == 2: savings = withdraw(savings) elif choice == 3:
view(savings) elif choice == 4: print("Thanks for using the savings monitor")
file = open("savings.txt","w") file.write(str(savings)) file.close() |
<< Previous: TextfilesNext: Hangman project >>