在循环内重新定义变量

时间:2016-04-19 18:02:39

标签: python python-2.7

我遇到了在代码中出现“未定义”错误的问题,或者我的变量被错误地重新定义了。我试图在每次执行循环时重新定义循环内的变量。但问题是(当我的变量在循环外定义时)我得到'变量未定义'错误,或者当循环重新初始化时变量不会改变和/或重置为零。

def game():
    scorePlayer = 0
    scoreAI = 0 #If I define it here I get the latter of the two errors explained.
    number = random.randint(1, 6)
    print ("Your score is ", scorePlayer, ". Your opponent's score is ", scoreAI, ".") #This is where it tells me it is referenced before defined if I define outside the loop.
    print (" ")
    print ("Rolling...")
    print (" ")
    time.sleep(2)
    print ("You have rolled a ", number, ".")
    print (" ")
    print ("Player, would you like to hold (enter 'hold') or roll (enter 'roll')?")
    print (" ")
    decide = raw_input(" ")
    if decide == 'hold':
        print (" ")
        scorePlayer = tempScorePlayer + scorePlayer
        gameAI()
    elif decide == 'roll': #changed to elif
        print (" ")
        if number == 1:
            print ("You have rolled a 1. You will not gain points from this turn.")
            print (" ")
            tempScorePlayer = 0
            gameAI()
        elif number >= 2: #changed to elif
            print (" ")
            tempScorePlayer = number + tempScorePlayer
            game()
    if scorePlayer >= 100:
        winPlayer()

我已经尝试在其他地方定义变量,这样它们就不会干扰循环,仍然无法使其工作。

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

dataservice.$inject = ['$http'];

我更改了tempScorePlayer变量,默认设置为0。

注意:def game(): scorePlayer = 0 scoreAI = 0 #If I define it here I get the latter of the two errors explained. number = random.randint(1, 6) print ("Your score is %d. Your opponent's score is %d."%(scorePlayer, scoreAI)) #This is where it tells me it is referenced before defined if I define outside the loop. print (" ") print ("Rolling...") print (" ") time.sleep(2) print ("You have rolled a %d.", number) print (" ") print ("Player, would you like to hold (enter 'hold') or roll (enter 'roll')?") print (" ") decide = raw_input(" ") if decide == 'hold': print (" ") scorePlayer += tempScorePlayer gameAI() if decide == 'roll': tempScorePlayer = 0 print (" ") if number == 1: print ("You have rolled a 1. You will not gain points from this turn.") print (" ") gameAI() if number >= 2: print (" ") tempScorePlayer += number game() if scorePlayer >= 100: winPlayer() 它等于tempScorePlayer += number