本地变量' first'在分配之前引用

时间:2015-07-13 19:45:01

标签: python

我得到本地变量'首先'在运行我的代码时,在分配之前引用了错误。

def start():

    global a
    a = [" "," "," "," "," "," "," "," "," "]
    global first
    first = randrange(2)

    def reverse():

        if first == 1:
            first = 0
        else:
            first = 1

        if first == 1:
            turn = "X"
        else:
            turn = "O"

这只是我的代码中发生错误的一部分。但是,当我将代码粘贴到IDLE中时,它没有问题,所以我不知道为什么会这样。

无论如何,我的完整代码(未完成的Tic Tac Toe):

from os import name
from os import system
from random import randrange
from time import sleep




def cls():
    system(['clear','cls'][name == 'nt'])


def start():

    global a
    a = [" "," "," "," "," "," "," "," "," "]
    global first
    first = randrange(2)

    def reverse():

        if first == 1:
            first = 0
        else:
            first = 1

        if first == 1:
            turn = "X"
        else:
            turn = "O"







    while True:

        reverse()
        cls()
        printBoard()
        print ""
        print "Its %s's turn." % (turn)
        print ""
        move = raw_input("Enter your move (1-9): ")

        if move.isdigit() == True:
            move = int(move)

            if move in range(9):
                move = move - 1
                if a[move] == " ":
                    a[move] = turn

                else:
                    print "Incorrect move: Place taken"
                    reverse()
                    sleep(2)    

            else:
                print "Incorrect move: Number out of range"
                sleep(2)    

        else:
            print "Incorrect move: Move not a number"
            sleep(2)







def printBoard():
    cls()
    print a[0],"|",a[1],"|",a[2]
    print       "---------"
    print a[3],"|",a[4],"|",a[5]
    print       "---------"
    print a[6],"|",a[7],"|",a[8]
start()

1 个答案:

答案 0 :(得分:3)

Python扫描函数体以获取任何赋值,如果它们没有显式声明global,则它会为该名称创建一个局部范围变量。因为您在first函数中分配给reverse(),并且您还没有明确声明first在该函数的范围内是全局的,所以python会创建一个名为的局部变量隐藏全球的first

比较之后的任务并不重要; python隐式声明函数开头的所有局部变量。

要解决此问题,您可以将first声明为reverse()函数中的全局,但正如其他人所说,应尽可能避免使用全局变量。