Latest web development tutorials

bucle anidado Python

lenguaje Python permite incrustado en un bucle dentro de otro bucle.

Python para la sintaxis del bucle anidado:

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python, mientras que la sintaxis del bucle anidado:

while expression:
   while expression:
      statement(s)
   statement(s)

Puede incrustar en otro bucle del cuerpo del bucle, como en el bucle while puede ser embebido para el bucle, por el contrario, puede incrustar en un bucle while para el bucle.

Ejemplo:

En el siguiente ejemplo se utiliza un número primo de salida de bucle anidado entre 2 y 100:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " 是素数"
   i = i + 1

print "Good bye!"

Los ejemplos de la salida anterior:

2 是素数
3 是素数
5 是素数
7 是素数
11 是素数
13 是素数
17 是素数
19 是素数
23 是素数
29 是素数
31 是素数
37 是素数
41 是素数
43 是素数
47 是素数
53 是素数
59 是素数
61 是素数
67 是素数
71 是素数
73 是素数
79 是素数
83 是素数
89 是素数
97 是素数
Good bye!