Sep-30-2023, 06:34 PM
EDIT: Okay I found this video that explains the issue well: https://www.youtube.com/watch?v=qsf_pM9Ge_g
but this issue does not exist in C++. So what is different about Python?
I was creating a little test to check if the pieces listed were part of a valid chess set. But I am getting an error when i call on pawnCounter in my function. It says "UnboundLocalError: cannot access local variable 'pawnCounter' where it is not associated with a value". But.... it's not a local variable. It is in the global scope; I defined it right at the beginning of my project:
but this issue does not exist in C++. So what is different about Python?
I was creating a little test to check if the pieces listed were part of a valid chess set. But I am getting an error when i call on pawnCounter in my function. It says "UnboundLocalError: cannot access local variable 'pawnCounter' where it is not associated with a value". But.... it's not a local variable. It is in the global scope; I defined it right at the beginning of my project:
pieces = {'wqueen': 'a6', 'wrook': 'g2', 'wking': 'a5', 'bpawn': 'b4', 'bking': 'h6', 'brook': 'a4'} pawnCounter = 0 def isValidChessBoard(): for piece in pieces: if 'pawn' in piece: pawnCounter += 1 if piece[0] != 'w' and piece[0] != 'b'\ or piece[1:] not in ('queen', 'pawn', 'rook', 'king', 'bishop', 'knight')\ or pawnCounter > 16: return False return TrueI looked online for help, and I found some advice saying to put "pawnConuter = pawnCounter" in the function parameters, like so:
def isValidChessBoard(pawnCounter = pawnCounter):or putting "global pawnCounter" at the start of the function:
def isValidChessBoard(): global pawnCounterand these do work. But I shouldn't have to do this, and it's too tedious to do every time for every variable. I don't understand why it's necessary. What is going on here? (P.S. This logic works in C++ without issue or needing to specify a global scope)