In this Python program, you will learn to print the X shape inside a rectangle 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, within this program, the nested if else statements will print the X pattern inside a rectangle of stars.
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('*', end='')
print()
Enter Rows = 15
\*************/
*\***********/*
**\*********/**
***\*******/***
****\*****/****
*****\***/*****
******\*/******
*******/*******
******/*\******
*****/***\*****
****/*****\****
***/*******\***
**/*********\**
*/***********\*
/*************\
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 stars pattern. For more Star 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('*', end='')
j += 1
print()
i += 1
Enter Rows = 13
\***********/
*\*********/*
**\*******/**
***\*****/***
****\***/****
*****\*/*****
******/******
*****/*\*****
****/***\****
***/*****\***
**/*******\**
*/*********\*
/***********\
This Python program allows the user to enter the rows. Next, the XinsideRectangle function uses nested for loops and nested if else conditions to print the stars on rows and columns of a rectangle pattern and display X as its diagonal.
def XinsideRectangle(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('*', end='')
print()
n = int(input("Enter Rows = "))
XinsideRectangle(n)