I'm confused about how Python scoping works here.
x = 1
def do(y):
y = y * 2
print y
print x
do(x)
print x
The code above produces this output:
1
2
1
The global variable remains unchanged, but in the function, the local variable prints out the correct changed value.
However, in this python-chess version I'm running below:
import chess
board = chess.Board()
def do(b):
b.push(list(b.legal_moves)[0]) #picks the first legal move
return b.fen()
print board.fen()
print do(board)
print board.fen()
It produces this output:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq - 1 1
Unexpectedly (at least for me) the global variable board
changes after the function has run.
I thought that a function creates a local variable instead of modifying the global variable - it seems you even need to imply specifically that you want to change it by using the global
keyword. It seems to work in the simple multiplication example I used, perhaps it's due to the .push()
method python-chess provides?
How would I then preserve the value of the global variable when running the function?
In this case, the output I desire should be:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq - 1 1
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1