I'm starting to learn Python and I would like to know why even if I defined my variable counterofplays above the function it is not being recognized in it.
counterofplays = 0 # this variable should be defined below
def tiktaktoe():
while playing:
isdigit = False
inRange = False
while not isdigit or not inRange:
playable = True
print(firstchoice,"turn")
index = input("Choose the index:\n" +
"1 | 2 | 3\n" +
"4 | 5 | 6\n" +
"7 | 8 | 9\n")
if index.isdigit():
isdigit = True
index = int(index)
if index in range(1,4) and row1[index-1][0] == ' ':
inRange = True
row1[index-1] = firstchoice if index == 3 else firstchoice + " | "
counterofplays += 1 # and here it marks error
elif index in range(4,7) and row2[index-4][0] == ' ':
inRange = True
row2[index-4] = firstchoice if index == 6 else firstchoice + " | "
counterofplays += 1
elif index in range(7,10) and row3[index-7][0] == ' ':
inRange = True
row3[index-7] = firstchoice if index == 9 else firstchoice + " | "
counterofplays += 1
else:
inRange = False
playable = False
else:
isdigit = False
playable = False
print("You've to choose a number")
sleep(1.3)
You should try defining counterofplays
Directly inside TikTakToe()
as global
And it shouldn't cause any problem. Since it doesn't seem that you use that variable outside of the aforementioned function you could also not set it as global
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.