2015-10-23 1 views
-1

Je reçois cette erreur après avoir ajouté les if déclarations sur le fond de mon code:UnboundLocalError: variable locale « n » référencé avant affectation

UnboundLocalError: local variable 'n' referenced before assignment

Toutes les idées ce qui est faux?

import random 

n=input('Write number of spaces you want to be playing on: ') 
if n < 3:  
    print "Gotta be more than 3 mate" 
    a = input('Would you like to end the program and try again?') 
    exit() 
else:  
    print"You're playing on %d lines" % n 

def DieGame(dieSize,numberDie): # dieSize (6 sides = 6),number of die (in this case,it'll be one 
    result = 0 
    value = 0 
    rounds = 1 

    while n > 1: 
     print "Round number " ,rounds 

     for i in range(0,numberDie):   # starting at 0 , number of die 
      result = random.randint(1,dieSize) #random number, 1 - size of dice(6 in this case) 
      print("On %d dice/die,you've rolled %d." % (i+1,result)) 
      value += result 

     print("Value of the roll/s %d of the dice/die is: %d" % (numberDie,value)) 

     if (n - value) > 1:  #if I'll get anything else than 1,its okay 
      print "New position: " ,n-value 
     if n == 1: 
      print "You've reached 1 space right before the finish,return back by 1." 
      n += 1     
     if (n-value) == 0: 

      a = input('Congratulations, you made it to the end! Press Enter to close the game.') 
      exit() 

     rounds += 1 
    else: 
     print "End" 
    DieGame(6,1) 
#------------------------------------------------------- 
#Gotta break the loop once I get to 0,or If I was to cross 0 to -1 and less.Can't cross 0. 

#If I'll be like 4 spaces from finish and I'll roll 6,I wont be able to move,gotta reach the last space. 

#Gotta make it reroll if I roll 1,add rolls to sum and then move forward by that number 
#if rolled for example 1+1+1(rerolling) + 3,add the sum together and move by 6. 

#if you step on the last space before the finish ,get one space back 
+1

Copie possible de [UnboundLocalError en Python] (http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python) –

Répondre

0

Votre problème est que n est affecté en dehors de la fonction. Cela entraînera un problème:

>>> n = 3 
>>> def x(): 
...  while n > 1: 
...   print("Iterating. n={}".format(n)) 
...   n = n - 1 
... 
>>> x() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in x 
UnboundLocalError: local variable 'n' referenced before assignment 

Attendu que:

>>> def y(): 
...  n = 3 
...  while n > 1: 
...   print("Iterating. n={}".format(n)) 
...   n = n - 1 
... 
>>> y() 
Iterating. n=3 
Iterating. n=2 

variables qui sont utilisées dans un champ lexical particulier doivent y être définis. Si la fermeture n'inclut pas n, la tentative de référence entraîne un problème.