While循环不中断(python)

时间:2019-04-04 17:31:10

标签: python while-loop break

此处根据母牛的条件值进行设置。如果 cows 等于 4 ,则while循环应该中断。 但是在这里, break 被视为不存在。

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 时,会打印正确,但 break 不会显示效果

如果我们稍微更改代码。 如果放置 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 正在工作。

2 个答案:

答案 0 :(得分:0)

您每次进行下一轮都将递归,这意味着当您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

答案 1 :(得分:0)

我刚刚尝试运行您的代码,并且脚本中的问题不仅仅是while循环。

但是请尝试使用以下小脚本来学习while循环的工作原理:

# While loop test

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

希望这会有所帮助。玩。