문제

나는 a 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
도움이 되었습니까?

해결책

코드를 올바르게 들여 쓰기 :

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 a 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

다른 팁

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

그만큼 is Python의 운영자는 아마도 당신이 기대하는 것을하지 않을 것입니다. 대신 :

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

나는 이것처럼 그것을 쓸 것이다 :

    if numpy.array_equal(tmp,universe_array):
        break

그만큼 is 운영자는 객체 아이덴티티를 테스트하며, 이는 평등과는 상당히 다른 것입니다.

아래와 같이 For Loop을 사용하여 수행합니다.

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top