0

I wanted my variable play to change whenever the turn changes so I made a function. If turn is even play will be variable O="O", vice versa for odd then I used the function even(turn) with turn=1, it displays O even though it should be X. Is my code below wrong in some way or it just doesn't work like that?

I'm making a tic tac toe program on repl.it, I've tried using manual change as in making 9 different copies to change the turns but its just too much work, I wanted to make a simpler code.

play=0
X="X"
O="O"

turn=1


def even(turn):
  if turn%2==0:
    play=O

  else:
    play=X



even(turn)
print(play)

I expect the output to be either O or X according to if the number is even or odd respectively.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nick
  • 3
  • 1
  • 2
    You have *two* variables named play, one global and one local (only inside even). Read up on `global` (but note that global state is generally best avoided). – jonrsharpe Dec 20 '18 at 12:11
  • Note that you'd better NOT use a global here: `def even(turn): return X if turn % 2 else 0; play = even(turn);` – bruno desthuilliers Dec 20 '18 at 12:22

1 Answers1

-1
play=0
X="X"
O="O"

turn=4


def even(turn):
  global play
  if turn%2==0:
     play=O

  else:
     play=X



even(turn)
print(play)

This is the correct way...define variable in your function with global keyword

Aliasgher Nooruddin
  • 534
  • 1
  • 6
  • 18