簡體   English   中英

無法在函數內循環時破壞python

[英]Unable to break a python while loop inside a function

該程序是我的GCSE計算機科學的蛇頭梯子程序(不用擔心,這只是練習),我很難用循環中存在的功能來中斷while循環。 這是代碼:

win = False

while win == False:
    print("Player 1 goes first.")

    def dice():
        roll = random.randint(1,6)
        return roll

    roll = dice()
    print("They roll a...",roll)
    player1+=roll

    def check():
        if player1 in ladders or player2 in ladders:
            print("A ladder has moved the player to a new position.")
        elif player1 in snakes or player2 in snakes:
            print("A snake has moved the player to a new position.")
        elif player1 >= 36:
            print("Congratulations. Player 1 has won the game.")
            win = True
        elif player2 >= 36:
            print("Congratulations. Player 2 has won the game.")
            win = True

    check()

    print("Player 1 is on square",player1)

顯然它還沒有完成,而這還不是全部代碼。 之后,它與player2相同。 在其上方有一個元組,檢查功能可以檢查玩家是否落在蛇或梯子上,但是我沒有添加代碼來實際使玩家在梯子/蛇上上下移動。

錯誤是while循環是一個無限循環。

我試圖將整個win = False或True更改為True,然后在我說win = True的地方使用break,但是即使Break顯然在循環內部,它也會返回“ break out loop”錯誤。 我想知道是否是因為我需要從函數中返回某些內容,但是我不太確定該怎么做。 只需將“ return win”置於兩個win = True以下,則不會有任何改變,而while循環仍會無限期地繼續。

我一直在這里這里尋找答案,但都沒有為我工作; 我認為我的情況略有不同。

發生這種情況是因為當您在函數中分配變量時,它使用了局部變量。 因此,為了快速解決問題,您可以添加global win檢查功能:

def check():
    global win
    if player1 in ladders or player2 in ladders:
        print("A ladder has moved the player to a new position.")
    elif player1 in snakes or player2 in snakes:
        print("A snake has moved the player to a new position.")
    elif player1 >= 36:
        print("Congratulations. Player 1 has won the game.")
        win = True
    elif player2 >= 36:
        print("Congratulations. Player 2 has won the game.")
        win = True

您可以在此處詳細了解變量類型-http: //www.python-course.eu/python3_global_vs_local_variables.php

同樣,將函數存儲在內部不是一個好主意,因為它將在每次迭代中創建函數,這是不好的。 因此最好在循環之外定義它們。

也許這就是您想要的? 請注意我是如何將這些功能從循環中取出的。 然后我放棄了使用布爾變量,因為周圍有更干凈的方法。 您可以while True使用,然后在滿足特定條件時break 如果希望在滿足特定條件時使循環回到起點,則可以使用continue

def dice():
        return random.randint(1,6)


def check():
        if player1 in ladders or player2 in ladders:
            print("A ladder has moved the player to a new position.")
        elif player1 in snakes or player2 in snakes:
            print("A snake has moved the player to a new position.")
        elif player1 >= 36:
            print("Congratulations. Player 1 has won the game.")
            return True
        elif player2 >= 36:
            print("Congratulations. Player 2 has won the game.")
            return True

while True:
    print("Player 1 goes first.")

    roll = dice()
    print("They roll a...",roll)
    player1 += roll

    if check():
        break

    print("Player 1 is on square",player1)

我並沒有真正觸及邏輯,但是將球員的分數傳遞給check有意義的。

暫無
暫無

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

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