Menu
CoddyTech

Handling Errors

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 89 of 92.

challenge icon

Challenge

Easy

Last, handle every choice that is not 1 to 5. Keep everything you wrote in the previous steps, and print:

Invalid choice. Please try again.

After the message, the loop reads the next choice as before.

Try it yourself

extends Node

func _ready():
	print("Welcome to the Daily Expense Tracker!")

	# Display the 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")

	# An empty array for the expenses
	var expenses: Array[float] = []

	while true:
		# Get the choice of the user
		var choice := OS.read_string_from_stdin()

		if choice == "1":
			# Add a new expense
			var amount := float(OS.read_string_from_stdin())
			expenses.append(amount)
			print("Expense added successfully!")
		elif choice == "2":
			# View all expenses
			if expenses.is_empty():
				print("No expenses recorded yet.")
			else:
				print("Your expenses:")
				for i in range(expenses.size()):
					print(i + 1, ". ", expenses[i])
		elif choice == "3":
			# Calculate the total and the average
			if expenses.is_empty():
				print("No expenses recorded yet.")
			else:
				var total := 0.0
				for expense in expenses:
					total += expense
				var average := total / expenses.size()
				print("Total expense: ", total)
				print("Average expense: ", average)
		elif choice == "4":
			# Clear all expenses
			expenses.clear()
			print("All expenses cleared.")
		elif choice == "5":
			# Exit the program
			print("Exiting the Daily Expense Tracker. Goodbye!")
			break

All lessons in Fundamentals

Practice on your own: Online GDScript compiler