虽然循环不破(python)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了虽然循环不破(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:
")]
    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:
")]
    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:
")]
        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

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

以上是关于虽然循环不破(python)的主要内容,如果未能解决你的问题,请参考以下文章

黄沙百战穿金甲,不破python终不还!

天下武功,无快不破,Python开发必备的6个库

循环通过 python 正则表达式匹配

Python - 循环加速 - 大型数据集

Python之如何优雅的重试

使用从循环内的代码片段中提取的函数避免代码冗余/计算开销