简体   繁体   中英

UnboundLocalError - variable referenced before assignment

I have the following function that I need help debugging. I am getting an error saying

"in checkValidMove i UnboundLocalError: local variable 'i' referenced before assignment"

How can I fix this? Please see the function below. Thanks!

def checkValidMove(board, row, col, tile):
    #check if spot is valid to place tile at 
    #check the row first

    for i in range(col -1, -1, -1):
        if board[row][i] == '.':
            break
    
    left = i + 1  <--- **ERROR HERE**

    for i in range(col + 1, len(board[0])):
        if board[row][i] == '.':
            break
    
    right = i - 1
    rowTotal = 0

    for i in range(left, right + 1):
        rowTotal += int(board[row][i])
    
    if not multipleOfFiveCheck(rowTotal + int(tile)):
        return False

    #check columns
    for i in range(row -1, -1, -1):
        if board[i][col] == '.':
            break

    up = i + 1

    for i in range(row + 1, len(board)):
        if board[i][col] == '.':
            break

    down = i - 1
    colTotal = 0

    for i in range(up, down + 1):
        colTotal += int(board[i][col])
    
    if not multipleOfFiveCheck(colTotal + int(tile)):
        return False
    
    return True

I'm assuming that since you want to access the value of i , it should be properly indented under the appropriate loops.

for i in range(col -1, -1, -1):
    if board[row][i] == '.':
        break
    left = i + 1  

(Do the same for the others)

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