Sebastian Sebastian - 1 year ago 67
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?


turn = True
def move(list, turn):

if turn == True:
sign_1 = "| x "
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

global turn
turn = False

return list, turn

move(board, turn)

Answer Source

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

a = f(a)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download