Handling Errors
Part of the Fundamentals section of Coddy's Python journey. Lesson 74 of 77.
Challenge
EasyLastly, handle the option where the choice of the user is not in the range 1 to 5. Output:
Invalid choice. Please try again.Try it yourself
print("Welcome to the Daily Expense Tracker!")
# Display menu once
print("\nMenu:")
print("1. Add a new expense")
print("2. View all expenses")
print("3. Calculate total and average expense")
print("4. Clear all expenses")
print("5. Exit")
# Initialize an empty list to store expenses
expenses = []
while True:
# Get user choice
choice = input()
if choice == "1":
# Add a new expense
amount = float(input())
expenses.append(amount)
print("Expense added successfully!")
elif choice == "2":
# View all expenses
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
print("Your expenses:")
for i in range(len(expenses)):
print(f"{i + 1}. {expenses[i]}")
elif choice == "3":
# Calculate total and average expense
if len(expenses) == 0:
print("No expenses recorded yet.")
else:
total = 0
for expense in expenses:
total += expense
average = total / len(expenses)
print(f"Total expense: {total}")
print(f"Average expense: {average}")
elif choice == "4":
# Clear all expenses
expenses = []
print("All expenses cleared.")
elif choice == "5":
# Exit the program
print("Exiting the Daily Expense Tracker. Goodbye!")
breakAll lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input11Lists Basics
Declaring a ListAccessing List ElementsModifying ListsList MethodsRecap - Product ListRecap - Reversed ListTuple14Daily Expense Tracker
Project OverviewExit The Program3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2Practice on your own: Online Python compiler