Bài 30
Đề bài: Viết chương trình tong hop kết hợp ca 3 phan:
ham, dictionary, try/except.
Quan ly điểm học sinh: them, sua, xoa, tìm kiem.
Xử lý lỗi day du khi nguoi dùng nhập sai.
Ví dụ:
Menu:
1. Them học sinh
2. Sua điểm
3. Xoa học sinh
4. Xem tat ca
5. Thoat
Đăng nhập để giáo viên có thể giao bài và nhận bài nộp của bạn.
Câu trả lời
du_lieu = {}
def them_hoc_sinh(ten, diem):
if not ten.strip():
raise ValueError("Ten khong duoc de trong")
if not 0 <= diem <= 10:
raise ValueError("Diem phai tu 0 den 10")
if ten in du_lieu:
raise KeyError(f"Hoc sinh '{ten}' da ton tai")
du_lieu[ten] = diem
print(f"Da them: {ten} - {diem}")
def sua_diem(ten, diem_moi):
if ten not in du_lieu:
raise KeyError(f"Khong tim thay '{ten}'")
if not 0 <= diem_moi <= 10:
raise ValueError("Diem phai tu 0 den 10")
du_lieu[ten] = diem_moi
print(f"Da sua diem cua {ten} thanh {diem_moi}")
def xoa_hoc_sinh(ten):
if ten not in du_lieu:
raise KeyError(f"Khong tim thay '{ten}'")
del du_lieu[ten]
print(f"Da xoa hoc sinh '{ten}'")
def xem_tat_ca():
if not du_lieu:
print("Chua co hoc sinh nao!")
return
print(f"\n{'Ten':15} {'Diem':8} {'Xep loai'}")
print("-" * 35)
for ten, diem in sorted(du_lieu.items()):
if diem >= 8: xl = "Gioi"
elif diem >= 6.5: xl = "Kha"
elif diem >= 5: xl = "Trung binh"
else: xl = "Yeu"
print(f"{ten:15} {diem:8.1f} {xl}")
while True:
print("\n1.Them 2.Sua diem 3.Xoa 4.Xem tat ca 5.Thoat")
chon = input("Chon: ").strip()
try:
if chon == "1":
ten = input("Ten: ")
diem = float(input("Diem: "))
them_hoc_sinh(ten, diem)
elif chon == "2":
ten = input("Ten can sua: ")
diem_moi = float(input("Diem moi: "))
sua_diem(ten, diem_moi)
elif chon == "3":
ten = input("Ten can xoa: ")
xoa_hoc_sinh(ten)
elif chon == "4":
xem_tat_ca()
elif chon == "5":
print("Tam biet!")
break
else:
print("Lua chon khong hop le, chon 1-5")
except ValueError as e:
print(f"Loi du lieu: {e}")
except KeyError as e:
print(f"Loi tim kiem: {e}")