如何停止While循环?

时间:2008-12-15 14:35:02

标签: 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

5 个答案:

答案 0 :(得分:16)

正确缩进代码:

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

您需要了解示例中的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

答案 1 :(得分: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

答案 2 :(得分:2)

Python中的is运算符可能无法达到预期效果。而不是:

    if numpy.array_equal(tmp,universe_array) is True:
        break

我会这样写:

    if numpy.array_equal(tmp,universe_array):
        break

is运算符测试对象标识,这与完全不同。

答案 3 :(得分:0)

我会使用for循环来完成它,如下所示:

def determine_period(universe_array):
    tmp = universe_array
    for period in xrange(1, 13):
        tmp = apply_rules(tmp)
        if numpy.array_equal(tmp, universe_array):
            return period
    return 0

答案 4 :(得分:-1)

这是 Charles Severance 的“python 或每个人”中关于编写 while True 循环的一段示例代码:

while True:
    line = input('> ')
    if line == 'done':
        break
    print(line)
print('Done!')

这帮助我解决了我的问题!