Python variable not initialized error, although it should be

I am writing a function intToRoman to convert numbers to roman numerals:

class Solution:
    def intToRoman(self, num: int) -> str:
        #Dictionary with keys for symbol and value for value
        symbols = { 
            'I' : 1, 
            'V' : 5,
            'X' : 10,
            'L' : 50,
            'C' : 100,
            'D' : 500,
            'M' : 1000
        } 
        str_form = str(num) #Get string form for extracting starting digit
        first_digit = str_form[0] # Get the first digit in string form for comparisons
        
        if first_digit != '4' and first_digit != '9': #If the value does not start with 4 or 9
            symbol_list = []
            
            for key,value in symbols.items(): # loop through to find the greatest key that does not return negative difference

                if (num >= value ):
                    best_key = key
                    
            
                else:
                    break;
            symbol_list += best_key # append this best key to the list
            number_to_subtract = symbols[best_key] 
            num = num - number_to_subtract # subtract the value from the number 
            symbol_list.append(self.intToRoman(num)) #recursion
            return ''.join(symbol_list)
        
        if (first_digit == '4' or first_digit == '9'): #If the value starts with 4 or 9
            symbol_list = []
            
            
            if (len(str_form) == 1 and first_digit == '4'):
                key_to_add = 'IV'
            elif ((len(str_form) == 1) and first_digit == '9'):
                key_to_add = 'IX'
            elif ((len(str_form) == 2) and first_digit == '4'):
                key_to_add = 'XL'
            elif ((len(str_form) == 2) and first_digit == '9'):
                key_to_add = 'XC'
            elif ((len(str_form) == 3) and first_digit == '4'):
                key_to_add = 'CD'
            elif ((len(str_form) == 3) and first_digit == '9'):
                key_to_add = 'CM'
            symbol_list += key_to_add #append to symbol_list
            if (len(str_form) > 1):
                truncated_str_num = str_form[1:] #get the truncated str num ; everything except first digit
                truncated_num = int(truncated_str_num)
                symbol_list.append(self.intToRoman(truncated_num)) #recursion
                return ''.join(symbol_list)
            else:
                return ''.join(symbol_list)
        
def main():
    solution = Solution()
    
    num = 3749
    expected = "MMMDCCXLIX"
    result = solution.intToRoman(num)
    print(f"Test case 3: num = {num}, expected = {expected}, result = {result}")


    num = 1994
    expected = "MCMXCIV"
    result = solution.intToRoman(num)
    print(f"Test case 3: num = {num}, expected = {expected}, result = {result}")

    num = 58
    expected = "LVIII"
    result = solution.intToRoman(num)
    print(f"Test case 3: num = {num}, expected = {expected}, result = {result}")

    

if __name__ == "__main__":
    main()'

For inputs that end with digits concerning the second if statement (starting with 4 or 9) it seems to work fine; see 3749 and 1994 above. But for inputs like 58, or even simpler just inputs like 8, or 7, I get the error:

File “intToRoman.py”, line 27, in intToRoman
symbol_list += best_key # append this best key to the list
^^^^^^^^^^^
UnboundLocalError: cannot access local variable ‘best_key’ where it is not associated with a value

I don’t understand how this is happening since best_key should be initialized no matter what in this clause:
if (num >= value ):
best_key = key
Since there is no number that doesn’t satisfy this condition. Is this my fault for not initializing best_key before entering the loop?

any help would be appreciated

New contributor

Z10 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật