Sebastian Sebastian - 29 days ago 9
Python Question

Returning False/True doesnt work

Here is my code, when I returned my "turn" it doesn't stay as false, but turns back to True again. Even though I returned the turn value as false.

What went wrong, and why?

code:

turn = True
def move(list, turn):

if turn == True:
sign_1 = "| x "
else:
sign_2 = "| o "

y_1 = int(input("Type the value of y: "))
x_1 = int(input("Type the value of x: "))
list[y_1-1][x_1-1] = sign_1
print_board(list)

global turn
turn = False
print(turn)

return list, turn

move(board, turn)
print(turn)

Answer

You need to learn about variable scope. The variable turn inside your function only exist inside that function meaning that as soon as you exit the function it is destroyed. Now you also have a turn defined outside but this one isn't modified at all by the function because turn from inside shadows turn from outside. To fix this your code, you should use what you return from the function to modify the turn and board from outside.

Here is a code that show a bit this variable scope thing:

a = 0

def f(a):
    a = 1
    return a

f(a)
print(a)
a = f(a)
print(a)
Comments