The looping statements can be used to create patterns by using the concept of a nested loop in python.
Nested Loop
When we place another loop within a loop then this is known as a nested loop. There can be multiple loops placed inside one another as a nested loop.
Example:
>>>for i in range(3): for j in range(3): print(“i={} and j={}” .format(i,j))
Output:
i=0 and j=0 i=0 and j=1 i=0 and j=2 i=1 and j=0 i=1 and j=1 i=1 and j=2 i=2 and j=0 i=2 and j=1 i=2 and j=2
The outer loop will execute 3 times and the inner loop will also execute 3 times. We will get a total of 9 outputs as the outer loop will run thrice from 0 to 2 and trigger the inner loop to run 3 times from 0 to 2 inside it. So the total number of times that we will get an output is 3*3 i.e. 9.
Note: It is also possible to get all these lines of output in a single line when required by using the Python end attribute.
Patterns:
We can obtain the desired pattern of certain characters or numbers by using loops.
Example:
>>>a=int(input(“Enter number of rows- ”)) >>>for i in range(1, a+1): #i represents row number for j in range(1, i+1): #j represents number of * print(“*”,end=“ “) print()
Input:
5
Output:
* ** *** **** *****
Input:
7
Output:
* ** *** **** ***** ****** *******
In the above program, we take the number of rows as input from the user and then run a nested for loop. The pattern will be printed according to the number of rows entered by the user. The i for loop will start executing from 1 to entered number of rows i.e. a and the j for loop will start from 1 to i. This means that the inner loop will execute as many times as i. This keeps incrementing after every execution of the loop.
Example:
>>>n= int(input(“Enter number of rows:”)) >>>for i in range(n): print(‘*’*n)
Input: 2
Output:
** **
Input: 4
Output:
**** **** **** ****
For the code snippet above we run a for loop from i equals to 1 to n. We print the ‘*’ into n rows n number of times in one row.
Example:
>>>a=int(input(“Enter number of rows- ”)) >>>for i in range(n): #i represents row number for j in range(n): #j represents number of * print(“*”,end=“ “)
Input: 2
Output:
****
Here, we get output in a continuous line as we do not use the ‘print()’ statement to change line after execution of each loop.