Escribí un bucle while
en una función, pero no sé cómo pararlo. Cuando no cumple su condición final, el bucle se eterniza. ¿Cómo puedo detenerlo?
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
Sólo tienes que sangrar el código correctamente:
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
Tienes que entender que la sentencia break
en tu ejemplo saldrá del bucle infinito que has creado con while True
. Así que cuando la condición break sea True, el programa saldrá del bucle infinito y continuará con el siguiente bloque indentado. Como no hay bloque siguiente en tu código, la función termina y no devuelve nada. Así que he arreglado tu código sustituyendo la sentencia break
por una sentencia return
.
Siguiendo tu idea de usar un bucle infinito, esta es la mejor forma de escribirlo:
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
El operador is
de Python probablemente no hace lo que usted espera. En lugar de esto:
if numpy.array_equal(tmp,universe_array) is True:
break
Yo lo escribiría así:
if numpy.array_equal(tmp,universe_array):
break
El operador is
comprueba la identidad de los objetos, que es algo muy distinto de la igualdad.