如何停止While循环?

NON*_*her 12 python while-loop

我写了while loop一个函数,但不知道如何阻止它.当它不满足其最终条件时,循环就永远不会发生.我怎么能阻止它?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break    #i want the loop to stop and return 0 if the 
                     #period is bigger than 12
        if period>12:  #i wrote this line to stop it..but seems it 
                       #doesnt work....help..
            return 0
        else:   
            return period
Run Code Online (Sandbox Code Playgroud)

Map*_*pad 17

只需正确缩进代码:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period
Run Code Online (Sandbox Code Playgroud)

您需要了解break示例中的语句将退出您创建的无限循环while True.因此,当break条件为True时,程序将退出无限循环并继续下一个缩进块.由于代码中没有后续块,因此函数结束并且不返回任何内容.所以我通过用break语句替换语句来修复代码return.

按照你的想法使用无限循环,这是编写它的最佳方式:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period
Run Code Online (Sandbox Code Playgroud)


Joe*_*orn 8

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period
Run Code Online (Sandbox Code Playgroud)