Hello dear readers! Welcome back to another edition of our tutorial on Python. In this tutorial guide, we are going to be studying about the nested loops in Python.
Python allows for the use of a loop inside another loop. This tutorial post contains a few examples to illustrate the concept.
Python allows for the use of a loop inside another loop. This tutorial post contains a few examples to illustrate the concept.
Syntax
The syntax for a nested loop is as follows -
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
The syntax for a nested while loop statement in Python is as follows -
while expression: while expression: statement(s) statement(s)
A final note on nested loops is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside of a while loop and vice versa.
Example
The following example makes use of a nested for loop in finding the prime numbers from 2 to 100 -
#!/usr/bin/python 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, " is prime" i = i + 1 print "Welcome to Web design tutorialz!"
Output
The following below is the output of the above example -
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime Welcome to Web design tutorialz!
Alright guys! This is where we are rounding up for this tutorial. In our next tutorial, we will be discussing about the Python break statement.
Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.