虽然循环不破(python)

问题描述 投票:0回答:2

这里根据奶牛的条件值设定。如果奶牛等于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()

然后休息正在运作。

python while-loop break
2个回答
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


0
投票

我只是尝试运行你的代码,这里的脚本问题比while循环更多。

但是试试这个小脚本来学习while循环是如何工作的:

# While loop test

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

希望这可以帮助。玩得开心。

© www.soinside.com 2019 - 2024. All rights reserved.