簡體   English   中英

在循環內重新定義變量

[英]Redefining a variable inside a loop

我的代碼中出現“未定義”錯誤,或者我的變量被錯誤地重新定義時遇到問題。 每次執行循環時,我都試圖重新定義循環內的變量。 但問題是(當我的變量在循環外定義時)我得到一個“變量未定義”錯誤,或者當循環重新初始化時變量沒有改變和/或被重置為零。

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()

我已經嘗試在其他地方定義變量,這樣它們就不會干擾循環,但仍然無法使其工作。

任何幫助將不勝感激,謝謝。

試試這個:

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 變量,默認設置為 0。

注意: tempScorePlayer += number等於tempScorePlayer = tempScorePlayer + number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM