[SOLVED] Why am I getting a "Referenced before assignment" error?

Issue

This Python program will determine whether the input array is a mountain array or not. I’ve found answers on stackoverflow for this same error in other programs I’ve made, but not this one. It seems to work without issue when a valid mountain array is the input, but I’m having issues when I change the first half of the test array to make it an invalid. Rather than it returning False, which is the goal, I’m getting this error: UnboundLocalError: local variable 'y' referenced before assignment. Also, I was getting the same error for the z variable, so I added the else statements and it fixed it. Can’t figure out why it didn’t fix the y variable as well. Here’s my code:

def validMountainArray(arr):
    maxElem = max(arr)
    maxIndex = arr.index(maxElem)
    if len(arr) < 3:
        return False
    else:
        beginning = arr[:maxIndex]
        end = arr[maxIndex + 1:]

        for i in range(1, len(beginning) - 1):
            if beginning[i + 1] > beginning[i]:
                y = True
            else:
                y = False
        for i in range(1, len(end) - 1):
            if end[i + 1] < end[i]:
                z = True
            else:
                z = False

        if y == True and z == True:
            return True
        else:
            return False

Solution

Those for-loops aren’t guaranteed to be executed. It’s possible that the range could end up with 0 numbers in it, and thus no loop will occur and y and/or z will never be assigned. To fix this, define those variables as False at the start of the function.

def validMountainArray(arr):
    y = False
    z = False
    maxElem = max(arr)
    maxIndex = arr.index(maxElem)
    # etc
    

Answered By – thisismy-stackoverflow

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.