Loops make our code more manageable and organized. Let us now see what the different types of loops are:
1. While Loop
2. For Loop
3. Nested Loop
The While Loop
The While loop can execute a set of commands till the condition is true While Loops are also called conditional loops.
Once the condition is met then the loop is finished
For example - Print from 1 to 10
Here, if we want to derive the loop from this scenario, we have the following conditions:
Condition: Write from 1 to 10 And the decision we are deriving is
Decision: Have we reached 10
Based on this we can write the below pseudocode:
x = 0
while x is not 10
x = x + 1
print(x)
The For Loop
For loop is needed for iterating over a sequence.
For example – We need to calculate the square of numbers present in a list.
Numbers= [1, 3, 5, 7, 13]
The pseudo code for this will look like below:
numbers = [1, 3, 5, 7, 13]
sq = 0
for x in numbers
sq = x * x
print(sq)
This is the result for the code
1
9
25
49
169
The Nested Loop
Loop can be nested in Python. A loop that occurs within another loop is called nested loop. Consider the below program.
numbers = [1, 2, 3]
alphabets = [a, b, c]
for num in numbers
for alphabet in alphabets
print(alphabet)
We have used two loops here. The outer loop, iterates over the numbers array and the inner loop iterates over the alphabet array. So each of the alphabets get printed 3 times. Finally, we have 9 items that are printed.
a
b
c
a
b
c
a
b
c