I wrote a while loop in a function, but don’t know how to stop it. When it doesn’t meet its final condition, the loop just go for ever. How can I stop it?
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
just indent your code correctly:
You need to understand that the
breakstatement in your example will exit the infinite loop you’ve created withwhile True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don’t return anything. So I’ve fixed your code by replacing thebreakstatement by areturnstatement.Following your idea to use an infinite loop, this is the best way to write it: