编写一个Python程序,使用for循环和while循环打印1和0组成的方框数字图案,并附带示例。
Python 使用For循环打印1和0方框数字图案的程序
此Python程序允许用户输入总行数和列数。接下来,我们使用Python嵌套For循环来迭代每一行和每一列的元素。在循环中,我们使用If语句来检查行号和列号是否为1或最大值。如果为真,Python则打印1,否则打印0。
# Python Program to Print Box Number Pattern of 1 and 0
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Box Number Pattern of 1 and 0")
for i in range(1, rows + 1):
for j in range(1, columns + 1):
if(i == 1 or i == rows or j == 1 or j == columns):
print('1', end = ' ')
else:
print('0', end = ' ')
print()

Python 使用While循环显示1和0方框数字图案的程序
此Python程序与上面的程序相同。但是,我们将For循环替换为了While循环。
# Python Program to Print Box Number Pattern of 1 and 0
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Box Number Pattern of 1 and 0")
i = 1
while(i <= rows):
j = 1;
while(j <= columns ):
if(i == 1 or i == rows or j == 1 or j == columns):
print('1', end = ' ')
else:
print('0', end = ' ')
j = j + 1
i = i + 1
print()
Please Enter the total Number of Rows : 8
Please Enter the total Number of Columns : 14
Box Number Pattern of 1 and 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
>>>
Python 0和1方框数字图案程序
如果您想让Python显示0和1数字组成的方框图案,请在打印语句中将1替换为0,将0替换为1。
# Python Program to Print Box Number Pattern of 1 and 0
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Box Number Pattern of 1 and 0")
for i in range(1, rows + 1):
for j in range(1, columns + 1):
if(i == 1 or i == rows or j == 1 or j == columns):
print('0', end = ' ')
else:
print('1', end = ' ')
print()
Please Enter the total Number of Rows : 9
Please Enter the total Number of Columns : 15
Box Number Pattern of 1 and 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
>>>