Search code examples
pythonarraysvariablesundefinedlocal

UnboundLocalError: local variable 'hoc_sinh_dang_nhap' referenced before assignment


P/S: The text in my code is vietnamese, if you are a foreign, you can use Google Translate to understand.

#1. Khởi tạo mảng và biến
ten = []
cac_cot_diem =[]
diem_trung_binh = []
thu_tu = 0
so_cot_diem = 0
so_hoc_sinh = 0
cot_diem_dang_nhap = 1
hoc_sinh_dang_nhap = 1
ten_hoc_sinh = 0

def chao_mung():
    print("<--Chào mừng đến với AvCalculator-->\nPhiên bản 0.1\nBởi Nguyễn Minh Trí - 6A4 - THCS Hoa Lư\n_______________________________________________")
    nhap_du_lieu()
def nhap_du_lieu():
    so_cot_diem = input("Vui lòng nhập số cột điểm: ")
    so_hoc_sinh = input("Vui lòng nhập số học sinh: ")
    print("Vậy là bạn sẽ nhập",so_cot_diem,"cột điểm cho",so_hoc_sinh,"học sinh.")
    while hoc_sinh_dang_nhap <= so_hoc_sinh:
        ten_hoc_sinh = input("Nhập tên học sinh thứ ", hoc_sinh_dang_nhap)
        ten.append(ten_hoc_sinh)
        return ten_hoc_sinh
        hoc_sinh_dang_nhap = hoc_sinh_dang_nhap + 1
def tinh_diem_trung_binh():
    # 2. Đi qua từng phần tử trong mảng
    for diem in cac_cot_diem:
        total = 0
        # 3. Tính điểm của 1 học sinh
        for value in diem:
            total = total + value
        diem_trung_binh = total / len(trials)
        diem_trung_binh.append(diem_trung_binh)
        #4. Hiển thị điểm lên màn hình
        while thu_tu < len(scores):
            print("Diem so cua",name[count],"la", scores[count])
            thu_tu = thu_tu + 1
chao_mung()

My code is an average calculator for teachers to calculate. As you can see in the code.

The output is:

<--Chào mừng đến với AvCalculator-->
Phiên bản 0.1
Bởi Nguyễn Minh Trí - 6A4 - THCS Hoa Lư
_______________________________________________
Vui lòng nhập số cột điểm: 10
Vui lòng nhập số học sinh: 10
Vậy là bạn sẽ nhập 10 cột điểm cho 10 học sinh.
Traceback (most recent call last):
  File "D:\Tris\My Coding Way\Nothing.py", line 37, in <module>
    chao_mung()
  File "D:\Tris\My Coding Way\Nothing.py", line 14, in chao_mung
    nhap_du_lieu()
  File "D:\Tris\My Coding Way\Nothing.py", line 19, in nhap_du_lieu
    while hoc_sinh_dang_nhap <= so_hoc_sinh:
UnboundLocalError: local variable 'hoc_sinh_dang_nhap' referenced before assignment

Thank you very much for your helping!!!


Solution

  • You have to explicitly tell the function that you are using a global variable.

    def nhap_du_lieu():
        global hoc_sinh_dang_nhap