14

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
4

5 回答 5

23

只需正确缩进您的代码:

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
于 2008-12-15T14:37:59.760 回答
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
于 2008-12-15T14:38:42.847 回答
3

Python 中的is运算符可能不符合您的预期。而不是这个:

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

我会这样写:

    if numpy.array_equal(tmp,universe_array):
        break

运算符测试对象身份,这is与相等性完全不同。

于 2008-12-15T18:03:02.217 回答
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
于 2008-12-16T19:03:27.803 回答
-1

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

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

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

于 2021-06-27T17:35:36.527 回答