简体   繁体   中英

Don't understand why I'm getting a NameError for a variable

I have a Tic Tac Toe game in Python, and right now its giving me a weird "Name Error". Here is the error:

NameError: name 'newspace' is not defined

Here is my code:

global newSpace
newSpace = " "

#Check for a win function:
def checkWin(player):
  if player == "X":
    newSpace = "🅧" #🅧
  else:
    newSpace = "🅞" #🅞
  if spaces[0] == player and spaces[1] == player and spaces[2] == player:
    spaces[0] = newspace
    spaces[1] = newspace
    spaces[2] = newspace
    return True
  if spaces[3] == player and spaces[4] == player and spaces[5] == player:
    spaces[3] = newspace
    spaces[4] = newspace
    spaces[5] = newspace
    return True
  if spaces[6] == player and spaces[7] == player and spaces[8] == player:
    spaces[6] = newspace
    spaces[7] = newspace
    spaces[8] = newspace
    return True
  if spaces[0] == player and spaces[3] == player and spaces[6] == player:
    spaces[0] = newspace
    spaces[3] = newspace
    spaces[6] = newspace
    return True
  if spaces[1] == player and spaces[4] == player and spaces[7] == player:
    spaces[1] = newspace
    spaces[4] = newspace
    spaces[7] = newspace
    return True
  if spaces[2] == player and spaces[5] == player and spaces[8] == player:
    spaces[2] = newspace
    spaces[5] = newspace
    spaces[8] = newspace
    return True
  if spaces[0] == player and spaces[4] == player and spaces[8] == player:
    spaces[0] = newspace
    spaces[4] = newspace
    spaces[8] = newspace
    return True
  if spaces[2] == player and spaces[4] == player and spaces[6] == player:
    spaces[2] = newspace
    spaces[4] = newspace
    spaces[6] = newspace
    return True
  return False

I know it's not the most efficient code, but i'm a beginner. In the top, I define newSpace and make it global, so I don't understand why it's giving me this error. Anyone know why? Thanks.

For reference, you can see my whole code here: https://repl.it/@LoveTheBears101/Tic-Tac-Toe . This is from line 1 - 67

区分大小写: newspace != newSpace

只需删除global newSpace ,这里不需要,如果newSpace没有提前声明。

In whole program there no error. But in your example problem is that you use "newSpace" and "newspace" variables. Python is case sensitive.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM