python - Local variable 'first' referenced before assignment -


this question has answer here:

i local variable 'first' referenced before assignment error when run code.

def start():      global     = [" "," "," "," "," "," "," "," "," "]     global first     first = randrange(2)      def reverse():          if first == 1:             first = 0         else:             first = 1          if first == 1:             turn = "x"         else:             turn = "o" 

that part of code error occurs. when paste code idle works no problem don't know why happening.

anyways, full code (unfinished tic tac toe):

from os import name os import system random import randrange time import sleep     def cls():     system(['clear','cls'][name == 'nt'])   def start():      global     = [" "," "," "," "," "," "," "," "," "]     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 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 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() 

python scans function body assignments, , if aren't explicitly declared global, creates local scope variable name. because assign first in reverse() function, , haven't explicitly declared first global within function's scope, python creates local variable named first hides global one.

it doesn't matter assignment comes after comparison; python implicitly declares local variables @ beginning of function.

to fix can declare first global within reverse() function, others have said, globals should avoided when possible.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -