Q:

Python break if a condition stays false for some time

I am writing a program for real time pitch detection. Here's the outline of the code :-
def pitch_detection :

    result = []
    while True :

        // apply pitch detection algorithm

        if pitch_energy > threshold :
            result.append(pitch)

    return result       

I want to brrak from the loop if pitch_energy > threshold is False for sometime 
What I am doing right now is timeout the loop after sometime. 
Like this :-
How would I stop a while loop after n amount of time?

A:

Save the time whenever you make an append to the list. Then compare it to the current time when you don't make a correction. If the time since you last made an append is greater than some threshold, you break:
def pitch_detection :

    result = []
    start = time.time()
    MAX_TIME_ALLOWED = 5 # seconds
    while True :

        // apply pitch detection algorithm

        if pitch_energy > threshold :
            result.append(pitch)
            start = time.time() # reset the time when we append.
        else:
            if (time.time() - start) > MAX_TIME_ALLOWED:
                break

    return result 

This assumes you actually want to use elapsed time to decide when to break. If you want to use number of iterations of the loop, just use a counter that starts at 0, and increment it in the else block, rather than time.time().
def pitch_detection :

    result = []
    no_append = 0
    MAX_TIME_ALLOWED = 5 # seconds
    while True :

        // apply pitch detection algorithm

        if pitch_energy > threshold :
            result.append(pitch)
            no_append = 0
        else:
            no_append += 1
            if no_append > MAX_TIMES_ALLOWED:
                break

    return result 

