In this Python program, you will learn to print the X or diagonal inside a rectangle or square pattern of stars 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, this program’s nested if else statements will print the X shape inside a rectangle of numbers pattern.
rows = int(input("Enter Rows = "))
for i in range(rows):
for j in range(rows):
if i == j or i + j == rows - 1:
if i + j == rows - 1:
print('/', end= '')
else:
print('\\', end='')
else:
print(i, end='') # Replace with i, j
print()
Enter Rows = 8
\000000/
1\1111/1
22\22/22
333\/333
444/\444
55/55\55
6/6666\6
/777777\
If you replace i with j, the result will be as shown below.
Enter Rows = 9
\1234567/
0\23456/8
01\345/78
012\4/678
0123/5678
012/4\678
01/345\78
0/23456\8
/1234567\
Instead of a For loop, this program uses the while loop to iterate the rows and columns and prints the X shape inside a rectangle of numbers pattern 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 i + j == rows - 1:
if i + j == rows - 1:
print('/', end= '')
else:
print('\\', end='')
else:
print(i, end='')
j += 1
print()
i += 1
Enter Rows = 9
\0000000/
1\11111/1
22\222/22
333\3/333
4444/4444
555/5\555
66/666\66
7/77777\7
/8888888\
This Python program allows the user to enter the rows. Next, the XinsideNumberRectangle function uses nested for loops and nested if else conditions to print the numbers on rows and columns of a rectangle pattern and display X as its diagonal.
def XinsideNumberRectangle(rows):
for i in range(rows):
for j in range(rows):
if i == j or i + j == rows - 1:
if i + j == rows - 1:
print('/', end='')
else:
print('\\', end='')
else:
print(i, end='') # Replace with i, j
print()
n = int(input("Enter Rows = "))
XinsideNumberRectangle(n)