In this Python program, you will learn to print the X pattern of numbers using for loop, while loop, and functions. The below example accepts the user-entered rows, and the nested for loops iterates the rows and columns. Next, the if else in this program will print the numbers in an X pattern.
rows = int(input("Enter Rows = "))
for i in range(rows):
for j in range(rows):
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
Enter Rows = 11
1 11
2 10
3 9
4 8
5 7
6
5 7
4 8
3 9
2 10
1 11
You may also try the below code and it will print different numbers on each side of the X pattern.
rows = int(input("Enter Rows = "))
for i in range(2 * rows - 1):
for j in range(2 * rows - 1):
if i == j or j == 2 * rows - 2 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
Enter Rows = 9
1 17
2 16
3 15
4 14
5 13
6 12
7 11
8 10
9
8 10
7 11
6 12
5 13
4 14
3 15
2 16
1 17
Instead of a For loop, this program uses the while loop to iterate the rows and columns and prints the X pattern of numbers at each position. For more Number pattern programs >> Click Here.
rows = int(input("Enter Rows = "))
i = 0
while i < rows:
j = 0
while j < rows:
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
j += 1
print()
i += 1
Enter Rows = 15
1 15
2 14
3 13
4 12
5 11
6 10
7 9
8
7 9
6 10
5 11
4 12
3 13
2 14
1 15
This Python program allows the user to enter the rows. Next, the XpatternNumber function uses nested for loops and if else prints the numbers on rows and columns of an X pattern.
def XpatternNumber(rows):
for i in range(rows):
for j in range(rows):
if i == j or j == rows - 1 - i:
print(j + 1, end='')
else:
print(' ', end='')
print()
n = int(input("Enter Rows = "))
XpatternNumber(n)