Las estructuras de repetitivas o bucles en Python al igual que otros lenguajes sirve para repetir un bloque de instrucciones. Se utilizan cuando se quiere ejecutar un conjunto de instrucciones un número finito de veces.
Las estructuras repetitivas son también llamadas bucles o ciclos y en el área de la programación es una herramienta muy útil.
Estructura for
La estructura for ejecuta instrucciones un número de veces determinada.
La sintaxis de un bucle for es la siguiente.
for variable in elemento iterable (lista, cadena, range, etc.):
cuerpo del bucleComo se puede visualizar la variable es el valor o elemento iterable que va a tomar, no es necesario definir la variable antes del bucle.
print("Estructura repetitiva for")
for i in [0, 1, 2, 3]:
print("EMENESES ", end="")
print("\n--------------")
Estructura repetitiva for
EMENESES EMENESES EMENESES EMENESES
--------------num1 = [11, 22, 19, 86]
for n in num1:
print(n)
11
22
19
86print("Estructura repetitiva for")
for i in []:
print("EMENESES ", end="")
print("\n--------------")
Estructura repetitiva for
#no imprime nada ya que la lista se encuentra vacía
--------------text = ["EMENESES", "DEVELOPERS", "DOCENCIA", "ONLINE"]
for x in text:
print(x)
EMENESES
DEVELOPERS
DOCENCIA
ONLINEfor x in "EMENESES":
print(x)
E
M
E
N
E
S
E
Stext = ["EMENESES", "DEVELOPERS", "DOCENCIA", "ONLINE"]
for x in text:
if x == "DOCENCIA":
break
print(x)
EMENESES
DEVELOPERSnum = [1, 2, 4, 3, 5, 8, 6]
stop = 50
for n in num:
print(n)
if n==stop:
break
else:
print('No se encontró el número', stop)
1
2
4
3
5
8
6
No se encontró el número 50num = 5
for f in range(1, 11):
mult = num * f
print(num, " x ", f, "=", mult)
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50Estructura while
La estructura de control while repetirá un conjunto de instrucciones mientras la condición dada se cumpla, cuando esta condición no se cumpla dejara de ejecutarse.
La sintaxis de un bucle while es la siguiente.
while expression
Cuerpo del whilei = 1
while i < 6: #Repite de uno a cinco el bucle
print("EMENESES")
i += 1
EMENESES
EMENESES
EMENESES
EMENESES
EMENESESa=1
num=5
while a<11:
mult = num * a
print(num, " x ", a, "=", mult)
a += 1
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50