En Python, los bucles «for» y «while» pueden utilizar la sentencia «else» el cual se ejecuta si el bucle termina sin ejecutar la sentencia «break«.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | def contains(haystack, needle): """ Throw a ValueError if `needle` not in `haystack`. """ for item in haystack: if item == needle: break else: # La sentencia "else" es una sentencia # adicional, que se ejecuta # solo si el bucle se completa sin ejecutar # la sentencia "break". raise ValueError('Needle not found') >>> contains([23, 'needle', 0xbadc0ffee], 'needle') None >>> contains([23, 42, 0xbadc0ffee], 'needle') ValueError: "Needle not found" |
Posiblemente el utilizar la setencia «else» para completar el bucle «for«, en ocasiones puede generar confusión, posiblemente es mejor realizar algo como:
1 2 3 4 5 | def better_contains(haystack, needle): for item in haystack: if item == needle: return raise ValueError('Needle not found') |
Incluso, para la sentencia, algo más pythonista sería:
1 2 | if needle not in haystack: raise ValueError('Needle not found') |
Nota:
En este caso, el objetivo es presentar la posibilida del uso del «else» en la sentencia «for.