简体   繁体   中英

Unbound Local Error in function

def pingpong(n):
    invisible_number = 0
    return_value = 0
    G = -1
    while invisible_number != n:
        if invisible_number > 10 and invisible_number < 100:
            invisible_number_ones_digit = invisible_number % 10
            invisible_number_tens_digit = invisible_number // 10
            return invisible_number_ones_digit and invisible_number_tens_digit
        if invisible_number > 100 and invisible_number < 1000:
            invisible_number_ones_digit = (invisible_number % 10) % 10
            invisible_number_tens_digit = (invisible_number % 10) // 10
            invisible_number_hundreds_digit = (invisible_number // 10) // 10
            return invisible_number_ones_digit and invisible_number_tens_digit and invisible_number_hundreds_digit
        if invisible_number % 7 == 0:
            return_value = return_value - G
            G = -1 * G

        elif invisible_number_ones_digit == 7 or invisible_number_tens_digit == 7 or invisible_number_hundreds_digit == 7:
            return_value = return_value - G
            G = -1 * G 
        else:
            return_value += G
        invisible_number += 1
    return return_value

This is for question number 3 here . I am only trying to get to up to 1000 for containing the digit 7 because I can't seem to find a pattern that I could use.

I'm assuming your UnboundLocalError is "local variable 'invisible_number_ones_digit' referenced before assignment". You set

invisible_number = 0

so if you call pingpong(n) where n is anything but 0, your code is going to fail when you reference the value of invisible_number_ones_digit , which you're currently doing in the elif . Same with any other variables which you are using before you've assigned them a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM