编写一个Python程序,使用For循环和While循环打印空心矩形星形图案,并附有示例。
Python 打印空心矩形星形图案程序(For 循环)
此 Python 程序允许用户输入矩形所需的总行数和列数。接下来,我们使用 Python 嵌套 For 循环来迭代每一行和每一列的值。在 For 循环中,我们使用了 If Else 语句:如果行或列元素为 0 或最大值 - 1,则 Python 打印 *;否则,打印空格。
# Python Program to Print Hollow Rectangle Star Pattern
rows = int(input("Please Enter the Total Number of Rows : "))
columns = int(input("Please Enter the Total Number of Columns : "))
print("Hollow Rectangle Star Pattern")
for i in range(rows):
for j in range(columns):
if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):
print('*', end = ' ')
else:
print(' ', end = ' ')
print()

Python 打印空心矩形星形示例 2
此 Python 程序允许用户输入自己的字符。接下来,它会打印用户指定字符的空心矩形图案。
# Python Program to Print Hollow Rectangle Star Pattern
rows = int(input("Please Enter the Total Number of Rows : "))
columns = int(input("Please Enter the Total Number of Columns : "))
ch = input("Please Enter any Character : ")
print("Hollow Rectangle Star Pattern")
for i in range(rows):
for j in range(columns):
if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):
print('%c' %ch, end = ' ')
else:
print(' ', end = ' ')
print()
Please Enter the Total Number of Rows : 12
Please Enter the Total Number of Columns : 20
Please Enter any Character : #
Hollow Rectangle Star Pattern
# # # # # # # # # # # # # # # # # # # #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# # # # # # # # # # # # # # # # # # # #
>>>
Python 使用 While 循环打印空心矩形星形程序
这个空心矩形星形程序与第一个示例相同。但是,我们用 While 循环替换了 For 循环。
# Python Program to Print Hollow Rectangle Star Pattern
rows = int(input("Please Enter the Total Number of Rows : "))
columns = int(input("Please Enter the Total Number of Columns : "))
print("Hollow Rectangle Star Pattern")
i = 0
while(i < rows):
j = 0
while(j < columns):
if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):
print('*', end = ' ')
else:
print(' ', end = ' ')
j = j + 1
i = i + 1
print()
Please Enter the Total Number of Rows : 10
Please Enter the Total Number of Columns : 22
Hollow Rectangle Star Pattern
* * * * * * * * * * * * * * * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * * * * * * * * * * * * * *
>>>