合計と平均
CoddyのPythonジャーニー「基礎」セクションの一部。レッスン 72/77。
チャレンジ
簡単合計費用と平均費用を計算するオプション(3)を処理します。
expenses リストが空の場合は、次のように出力します。
No expenses recorded yet.それ以外の場合は、次の形式でリストを出力します。
Total expense: 600.0
Average expense: 200.0先ほど入力した費用が 300、200、100 だったとします。(この順番です!)
自分で試してみよう
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基礎のすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ