如何停止 While 循环?

14 投票
5 回答
270063 浏览
提问于 2025-04-11 20:48

我在一个函数里写了一个while循环,但是我不知道怎么让它停止。当它没有满足结束的条件时,这个循环就会一直执行下去。那我该怎么让它停下来呢?

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 个回答

2

在Python中,is这个操作符可能和你想的不太一样。你可能以为它是用来比较两个东西是否相等,但其实不是这样的。

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

我会这样写:

    if numpy.array_equal(tmp,universe_array):
        break

其实,is操作符是用来检查两个对象是否是同一个东西,这和简单的相等比较是完全不同的概念。

7

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这就像是把水从一个杯子倒到另一个杯子一样。

有些时候,我们会遇到一些问题,比如数据的格式不对,或者我们想要的数据没有被正确获取。这就像是你想喝水,但杯子里却是果汁,这时候你就需要想办法把果汁倒掉,换成水。

在解决这些问题时,我们可能会用到一些工具和方法。比如,我们可以使用一些函数来帮助我们处理数据,就像是用漏斗来把果汁倒掉,确保最后得到的是水。

总之,编程就像是在做一系列的操作,目的是为了让数据变得更有用,最终达到我们想要的结果。

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
25

只需要正确缩进你的代码:

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 语句换成了 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

撰写回答