PythonPython3java
 

Python Loop nesting

Python The language allows you to embed another loop in a loop body.

Python for Loop nesting syntax:

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

Python while Loop nested syntax´╝Ü

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

You can embed other loop bodies in the loop body, such as the for loop in the while loop. Instead, you can embed a while loop in a for loop.

Instance:

The following example uses a nested loop to output a prime number between 2 and 100:

div class="example">

Instance

#!/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, " Prime number" i = i + 1 print "Good bye!"

The output of the above example:

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






Welookups is optimized for learning.© Welookups 2018 -
All Right Reserved and you agree to have read and accepted our term and condition