Python-patterns

Points to remember:
  • Looping is used to repeat a set of statements a certain number of times.
  • Looping in Python can be implemented using while and for.
  • The statements in the while block executes until the test condition remains true.
  • The else part executes if the loop ends without a break.
  • ‘for’ can be used for all the purposes for which a ‘while’ is used.
  • ‘for’ is generally used for processing lists, tuples, matrices, etc.
  • range (n) means values from 0 to (n – 1).
  • range (m, n) means all the values from m to (n – 1).
  • A loop can be nested in a loop.

The following examples show how to assign values to the counters of the inner and the outer loops to carry out the pattern task. The patterns, as such, may not be very useful. However, doing the following program would help the programmer to comprehend the concept of nesting.

Write a program to generate the following pattern in Python.

*

* *

* * *

* * * *

The number of rows would be entered by the user.

Solution: The number of rows n, will determine the value of the counter (from 0 to n). The value of i denotes the row number in the following program. In each row, the number of stars is equal to the row number. The values of j, in each iteration, denotes the number of stars in each row. This loop is therefore nested. Also, note that after the inner loop ends a new line is printed using the print() function.

Program
>>>
n = input('Enter the number of rows')
m = int(n)
*k=1
for i in range(m):
   for j in range(1, i+2):
     print('*', end=" ")
   print()

Write a program to generate the following pattern in Python.

2

2 3

2 3 4

2 3 4 5

The number of rows would be entered by the user.

Solution: The number of rows, entered by the user, will determine the value of i (from 0 to n). The value of i denotes the row number in the following program. In each row, the number of elements is equal to the row number. The values of j in each iteration denote the number of elements in each row. This loop is therefore nested. The element printed is the value of j+1. Also note that after the inner loop ends a new line is printed using the print() function.

n = input('Enter the number of rows')
m = int(n)
k=1
for i in range(m):
   for j in range(1, i+2):
     print(j+1, end=" ")
   print()

Write a program to generate the following pattern in Python.

1

2 3

4 5 6

7 8 9 10

The number of rows would be entered by the user.

Solution: The value of i denotes the row number in the following program. In each row, the number of elements is equal to the row number. The values of i in each iteration will denote the number of elements in each row. This loop is therefore nested. The element printed is the value of k, which starts from 1 and incrementally increases in each iteration. Also note that after the inner loop ends a new line is printed using the print() function.

Program
n = input('Enter the number of rows')
m = int(n)
k=1
for i in range(m):
   for j in range(1, i+2):
     print(k, end=" ")
     k=k+1
   print()

Write a program to generate the following pattern in Python.

*

***

*****

*******

*********

The number of rows would be entered by the user.

Solution: The value of i denotes the row number in the following program. In each row, the number of stars is equal to the row number. The values of k in each iteration denote the number of stars in each row, which ranges from 0 to (2*i +1). This loop is therefore nested. The leading spaces are governed by the value of j, which ranges from 0 to (m-i-1). This is because if the value of i is 0, the number of spaces should be 4 (if the value of n is 5). In case the value of i is 1, the number of spaces should be 3 and so on. Also note that after the inner loop ends a new line is printed using the print() function.

Program
n = input('Enter the number of rows')
m = int(n)
for i in range(m):
   for j in range(0, (m-i-1)):
     print(' ', end="")
   for k in range(0, 2*i+1):
     print('*',end="")
print()

Generate a n × m, matrix, wherein each element (aij), is given by

ai, j = 5 × (i + j)2

Solution: The concept has been explained in the above discussion. There will be two loops; the outer loop for the number of rows and the inner loop for the number of columns.

Program

n = int(input('Enter the number of rows')) m = int(input('Enter the number of columns')) for i in range (n): for j in range(m): element = 5*(i+j)*(i+j) print(element, sep=' ', end= ' ') print() >>>

Output

Enter the number of rows3

Enter the number of columns3

0 5 20

5 20 45

20 45 80

Handling list of lists

In the following program the first list’s second element is itself a list. Its first element can be accessed by writing hb[0][1] and the first letter of the first element of the nested list would be hb[0][1][0].

Program

>>>
hb=["Programming in C#",["amrita University campus", 2015]]
rm=["SE is everything",["Obscure shops", 2015]]
authors=[hb, rm]
print(authors)
print("List:\n"+str(authors[0])+"\n"+str(authors[1])+"\n")
print("Name of books\n"+str(authors[0][0])+"\n"+
                                  str(authors[1][0])+"\n")
print("Details of the books\n"+str(authors[0][1])+"\n"+
                                  str(authors[1][1])+"\n")
print("\nLevel 3 Publisher 1\t:"+str(authors[0][1][0]))

Output


[['Programming in C#', ['amrita University campus', 2015]],
        ['SE is everything', ['Obscure shops', 2015]]]
List:
['Programming in C#', ['amrita University campus', 2015]]
['SE is everything', ['Obscure shops', 2015]]
Name of books
Programming in C#
SE is everything
Details of the books
['amrita University campus', 2015]
['Obscure shops', 2015]
Level 3 Publisher 1      :amrita University campus

Another example of the use of loops in processing nested lists. The user is expected to observe the output and infer what happened.
Program

hb=["Programming in C#",["cloudvikas", 2015]]
rm=["SE is everything",["Obscure Publishers", 2015]]
writer=[hb, rm]
print(writer)
for i in range(len(writer)):
   for j in range(len(writer[i])):
     for k in range(len(writer[i][j])):
       print(str(i)+" "+str(j)+" "+str(k)+"  "+str(writer[i][j][k])+"\n")
print()
Output

[['Programming in C#', ['cloudvikas', 2015]], ['SE is everything', ['Obscure Publishers', 2015]]]
0 0 0 P
0 0 1 r
0 0 2 o
0 0 3 g
0 0 4 r
0 0 5 a
0 0 6 m
0 0 7 m
0 0 8 i
0 0 9 n
0 0 10 g
0 0 11
0 0 12 i
0 0 13 n
0 0 14
0 0 15 C
0 0 16 #
0 1 0 cloudvikas
0 1 1 2015
1 0 0 S
1 0 1 E
1 0 2
1 0 3 i
1 0 4 s
1 0 5
1 0 6 e
1 0 7 v
1 0 8 e
1 0 9 r
1 0 10 y
1 0 11 t
1 0 12 h
1 0 13 i
1 0 14 n
1 0 15 g
1 1 0 Obscure Publishers
1 1 1 2015

To print given number of *s in a row

if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print('*', end=' ')


Output:
Enter n value:4
* * * * 
Process finished with exit code 0

To print square pattern with * symbols


if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print('* '*n)

Output:
Enter n value:6
* * * * * * 
* * * * * * 
* * * * * * 
* * * * * * 
* * * * * * 
* * * * * * 

Process finished with exit code 0

To print square pattern with provided fixed digit.

Ex:

Enter n value:4
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4


if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print((str(n)+' ')*n)

Output: 
Enter n value:6
6 6 6 6 6 6 
6 6 6 6 6 6 
6 6 6 6 6 6 
6 6 6 6 6 6 
6 6 6 6 6 6 
6 6 6 6 6 6 

Process finished with exit code 0

To print square pattern with provided fixed digit in every row

Example:

Enter n value:6
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6


if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print((str(i+1)+' ')*n)

output:
Enter n value:7
1 1 1 1 1 1 1 
2 2 2 2 2 2 2 
3 3 3 3 3 3 3 
4 4 4 4 4 4 4 
5 5 5 5 5 5 5 
6 6 6 6 6 6 6 
7 7 7 7 7 7 7 

Process finished with exit code 0

To print square pattern with fixed alphabet symbol

Example-Enter n value:4
X X X X
X X X X
X X X X
X X X X


if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print(('Z ')*n)

Output:
Enter n value:6
Z Z Z Z Z Z 
Z Z Z Z Z Z 
Z Z Z Z Z Z 
Z Z Z Z Z Z 
Z Z Z Z Z Z 
Z Z Z Z Z Z 

Process finished with exit code 0

To print square pattern with alphabet symbols

A A A A A A A
B B B B B B B
C C C C C C C
D D D D D D D
E E E E E E E
F F F F F F F
G G G G G G G


if __name__ == '__main__':
    n = int(input('Enter n value:'))
    for i in range(n):
        print((chr(65+i)+' ')*n)

Output:
Enter n value:5
A A A A A 
B B B B B 
C C C C C 
D D D D D 
E E E E E 

Process finished with exit code 0

To print square pattern with digits

1 2 3
1 2 3
1 2 3


if __name__ == '__main__':
    n = int(input('Enter No Of Rows:'))
    for i in range(n):
        for j in range(n):
            print(str(j + 1), end=' ')
        print()

output:
Enter No Of Rows:5
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

To print square pattern with alphabet symbols in dictionary order

A B C D
A B C D
A B C D
A B C D


if __name__ == '__main__':
    n = int(input('Enter No Of Rows:'))
    for i in range(n):
        for j in range(n):
            print(chr(65 + j), end=' ')
        print()

Output
Enter No Of Rows:5
A B C D E 
A B C D E 
A B C D E 
A B C D E 
A B C D E 

To print square pattern with digits in descending order

3 3 3
2 2 2
1 1 1


if __name__ == '__main__':
    n = int(input('Enter No Of Rows:'))
    for i in range(n):
        print((str(n - i) + ' ') * n)

Output:
Enter No Of Rows:5
5 5 5 5 5 
4 4 4 4 4 
3 3 3 3 3 
2 2 2 2 2 
1 1 1 1 1 

To print square pattern with alphabets in reverse of dictionary order

C C C
B B B
A A A


if __name__ == '__main__':
    n = int(input('Enter No Of Rows:'))
    for i in range(n):
        print((chr(64+n-i)+' ')*n)

Output
Enter No Of Rows:6
F F F F F F 
E E E E E E 
D D D D D D 
C C C C C C 
B B B B B B 
A A A A A A