簡體   English   中英

雖然循環不破(python)

[英]While loop not breaking(python)

這里根據奶牛的條件值設定。 如果奶牛等於4,那么while循環應該會破裂。 但是這里的休息被視為不存在。

import random

r = random.randint
def get_num():
 return "{0}{1}{2}{3}".format(r(1, 9), r(1, 9), r(1, 9), r(1, 9))

n = get_num()
print(n)
n = [z for z in str(n)]

def game():
    cows = 0
    bulls = 0
    print()

    usr_num = [i for i in input("enter:\n")]
    usr_set = set(usr_num)

    while True:
        for x in usr_set:
            if usr_num.count(x) >= n.count(x):
                cows += n.count(x)
                bulls += usr_num.count(x) - n.count(x)
            elif usr_num.count(x) < n.count(x):
                cows += usr_num.count(x)
                bulls += n.count(x) - usr_num.count(x)

        print("cows: ", cows, "   bulls: ", bulls)

        if cows == 4:
            print("correct!")
            break
        else:
            game()

game()

奶牛 = 4時 ,打印正確打破沒有顯示其效果

如果我們稍微改變代碼。 如果我們放4 (If語句)代替奶牛

def game():
    cows = 0
    bulls = 0
    print()

    usr_num = [i for i in input("enter:\n")]
    usr_set = set(usr_num)

    while True:
        for x in usr_set:
            if usr_num.count(x) >= n.count(x):
                cows += n.count(x)
                bulls += usr_num.count(x) - n.count(x)
            elif usr_num.count(x) < n.count(x):
                cows += usr_num.count(x)
                bulls += n.count(x) - usr_num.count(x)

        print("cows: ", cows, "   bulls: ", bulls)

        if 4 == 4:
            print("correct!")
            break
        else:
            game()

game()

然后休息正在運作。

每次執行另一輪時都會遞歸,這意味着當您break ,您最終會突破最后一次遞歸。

而不是使用尾遞歸,嘗試移動while True:

def game():
    while True:
        cows = 0
        bulls = 0
        print()

        usr_num = [i for i in input("enter:\n")]
        usr_set = set(usr_num)

        for x in usr_set:
            if usr_num.count(x) >= n.count(x):
                cows += n.count(x)
                bulls += usr_num.count(x) - n.count(x)
            elif usr_num.count(x) < n.count(x):
                cows += usr_num.count(x)
                bulls += n.count(x) - usr_num.count(x)

        print("cows: ", cows, "   bulls: ", bulls)

        if cows == 4:
            print("correct!")
            break

這樣我們就不會遞歸,所以我們的突破就像你期望的那樣:看看repl.it

我只是嘗試運行你的代碼,這里的腳本問題比while循環更多。

但是試試這個小腳本來學習while循環是如何工作的:

# While loop test

i=0
j=5
while True:
    if i >= j:
        break
    else:
        print(f"{i} < {j}")
        i +=1

希望這可以幫助。 玩得開心。

暫無
暫無

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

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