Menu
CoddyTech

Tổng và trung bình

Thuộc phần Nền tảng cơ bản trong hành trình Python của Coddy. Bài học 72 trên 77.

challenge icon

Thử thách

Dễ

Xử lý tùy chọn tính tổng và chi phí trung bình (3).

Nếu danh sách chi phí trống, hãy in ra:

No expenses recorded yet.

Nếu không, hãy in danh sách theo định dạng sau:

Total expense: 600.0
Average expense: 200.0

Giả sử các khoản chi phí đã nhập trước đó là 300, 200 và 100. (Theo đúng thứ tự đó!)

Tự làm thử

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 == "5":
        # Exit the program
        print("Exiting the Daily Expense Tracker. Goodbye!")
        break

Tất cả bài học trong Nền tảng cơ bản

Tự luyện tập: Trình biên dịch Python online