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 25 Answers
just indent your code correctly:
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 You need to understand that the break statement in your example will exit the infinite loop you've created with while 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 the break statement by a return statement.
Following your idea to use an infinite loop, this is the best way to write 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 if period>12: #i wrote this line to stop it..but seems its doesnt work....help.. period = 0 break return period 3def 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 5The is operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True: break I would write it like this:
if numpy.array_equal(tmp,universe_array): break The is operator tests object identity, which is something quite different from equality.
I would do it using a for loop as shown below :
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 Here's a piece of example code from Charles Severance's "python or everybody" about writing while True loops:
while True: line = input('> ') if line == 'done': break print(line) print('Done!') This helped me with my problem!
1