Monday, December 30, 2019

Nested Loops

Welcome Friends!

In today's blog, we will discuss nested loops. So, what is a nested loop? A nested loop is a loop within a loop. To explain this, let's take an example of a basic loop and then a nested loop, assuming we want to print a table of 5.

# Print a table from 2 to 7
for i in range(1, 11):
    result = 5 * i 
    print("5 * " + str(i) + " = " + str(result))

The result will look like this:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Now, if we want to print similar tables for number 2 to 7, we will have to add another loop to iterate through numbers from 2 to 7. Here is an example.   
# Print a table from 2 to 7
for number in range(2, 8): 
    for i in range(1, 11):
        result = number * i 
        print(str(number) + " * " + str(i) + " = " + str(result))


Once you execute the statement, we will see tables from 2 through 7.

A nested loop doesn't necessarily have to be only for "for" loop, it can be for a "while" or "if" loop or a combination of any. To explain this, let's try to find all even numbers between 1 and 10.
# Print an even number between 1 and 10
for number in range(1, 11): 
    if number % 2 == 0: 
        print(str(number) + " is an even number")
2 is an even number
4 is an even number
6 is an even number
8 is an even number
10 is an even number

I hope you have enjoyed this. In our next post, we will play around with formatting. Stay tuned.                      

No comments:

Post a Comment