Loops simplify the need of writing multiple lines with instructions (code) and it simplify the code by providing code re-usability.
For
The for loop is used to iterate a statement several numbers of times. We use a for loop to execute the statement until the given condition is satisfied and also the for loop is used if the number of iterations is known in advance.
In python, the syntax of for loop is the following:
Now, let’s take a look of python code example of a for loop:
In this example, we call a variable called “number” and we iterate from number 0 to 10, storing temporally a number in the variable and printing it for each loop.
While
In while loop a part of the code is executed as long as a given condition is true. We can take as an example, the buying house loop as mentioned above.
The syntax for python for while loop is the following:
while (true): Do something |
Now, let’s take a look to a real python code example of while loop:
On the example above, we create a variable “number”. After that, we create a while loop condition, that prints the variable “number” if number is less than 11. For each loop in while, the number variable is incremented by one. When the number is 11, the while loop breaks and the code ends.
Important: You need to be careful while using while loops. If your while loop doesn’t meet a condition, it runs continuously for an infinite amount of time until you stop it with an escape character or manually close the running process.
Nested Loops
Nested loops in simple terms is a loop inside a loop. The inner loop is executed n number of times for every iteration of the outer loop. It can be applied in for loops and in while loops.
A nested for loop, in terms of syntax in Python is the following:
Now, let’s take a look to a real python code example of a nested for loop:
Besides the nested for loop, you can also make a nested combination between while loop and a for loop. Take a look to the next example:
In this example above, we created a while loop with a for loop nested inside the while loop.
To finish, you can also do a nested while loop, in other words, you can do a while inside a while. Take a look to the next example:
The nested while example shows that the inner while finish first and after that, the outer while progresses and finishes.