Menu
CoddyTech

Xóa liên hệ

Thuộc phần Logic và luồng chương trình trong hành trình GDScript của Coddy. Bài học 28 trên 78.

challenge icon

Thử thách

Dễ

Xử lý lựa chọn 4, xóa một liên hệ. Giữ lại mọi thứ bạn đã viết ở các bước trước.

Viết delete_contact(contact_book: Dictionary). Hàm này đọc một tên. Nếu tên đó có trong contact_book, hãy xóa liên hệ đó và in ra:

Contact deleted successfully!

Nếu không, hãy in ra Contact not found!

Trong vòng lặp, thêm một nhánh elif cho "4" để gọi delete_contact(contact_book).

Tự làm thử

extends Node

func _ready():
	var contact_book := {}

	while true:
		display_menu()
		var choice := OS.read_string_from_stdin()
		if choice == "1":
			add_contact(contact_book)
		elif choice == "2":
			view_contact(contact_book)
		elif choice == "3":
			edit_contact(contact_book)
		elif choice == "6":
			break

func display_menu() -> void:
	print("Contact Book Menu:")
	print("1. Add Contact")
	print("2. View Contact")
	print("3. Edit Contact")
	print("4. Delete Contact")
	print("5. List All Contacts")
	print("6. Exit")

func add_contact(contact_book: Dictionary) -> void:
	var contact_name := OS.read_string_from_stdin()
	if contact_book.has(contact_name):
		print("Contact already exists!")
		return
	var phone := OS.read_string_from_stdin()
	var email := OS.read_string_from_stdin()
	var address := OS.read_string_from_stdin()
	contact_book[contact_name] = {"phone": phone, "email": email, "address": address}
	print("Contact added successfully!")

func view_contact(contact_book: Dictionary) -> void:
	var contact_name := OS.read_string_from_stdin()
	if contact_book.has(contact_name):
		var contact: Dictionary = contact_book[contact_name]
		print("Name: ", contact_name)
		print("Phone: ", contact["phone"])
		print("Email: ", contact["email"])
		print("Address: ", contact["address"])
	else:
		print("Contact not found!")

func edit_contact(contact_book: Dictionary) -> void:
	var contact_name := OS.read_string_from_stdin()
	if contact_book.has(contact_name):
		var contact: Dictionary = contact_book[contact_name]
		var phone := OS.read_string_from_stdin()
		var email := OS.read_string_from_stdin()
		var address := OS.read_string_from_stdin()
		if phone != "":
			contact["phone"] = phone
		if email != "":
			contact["email"] = email
		if address != "":
			contact["address"] = address
		print("Contact updated successfully!")
	else:
		print("Contact not found!")

Tất cả bài học trong Logic và luồng chương trình

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