编写一个 Python 程序,使用 While 循环和 For 循环交替打印 1 和 0,并附带示例。
Python 程序打印交替列中的 1 和 0(使用 For 循环)
此 Python 程序允许用户输入总行数和列数。接下来,我们使用 Python 嵌套 For 循环,打印 1 和 0,直到达到用户指定的行数和列数。
# Python Program to Print 1 and 0 in alternative Columns
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Print Number Pattern - 1 and 0 in alternative Columns")
for i in range(1, rows + 1):
for j in range(1, columns + 1):
if(j % 2 == 0):
print('0', end = ' ')
else:
print('1', end = ' ')
print()

Python 程序使用 While 循环在交替列中显示 1 和 0
在此 Python 程序中,我们将 For 循环替换为 While 循环。
# Python Program to Print 1 and 0 in alternative Columns
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Print Number Pattern - 1 and 0 in alternative Columns")
i = 1
while(i <= rows):
j = 1
while(j <= columns):
if(j % 2 != 0):
print('1', end = ' ')
else:
print('0', end = ' ')
j = j + 1
i = i + 1
print()
Python 输出交替列中的 1 和 0
Please Enter the total Number of Rows : 7
Please Enter the total Number of Columns : 12
Print Number Pattern - 1 and 0 in alternative Columns
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
Python 程序在不使用 If 的情况下显示交替列中的 1 和 0
在此 Python 程序中,我们在打印语句中查找偶数或奇数列。通过这种方式,您可以避免在嵌套 For 循环中使用额外的 If 语句。
# Python Program to Print 1 and 0 in alternative Columns
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Print Number Pattern - 1 and 0 in alternative Columns")
for i in range(1, rows + 1):
for j in range(1, columns + 1):
print('%d' %(j % 2), end = ' ')
print()
Python 输出交替列中的 1 和 0
Please Enter the total Number of Rows : 5
Please Enter the total Number of Columns : 8
Print Number Pattern - 1 and 0 in alternative Columns
1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0
Python 程序在交替列中显示 0 和 1
如果要交替打印列中的 0 和 1,则将打印语句中的 1 替换为 0,将 0 替换为 1。
# Python Program to Print 1 and 0 in alternative Columns
rows = int(input("Please Enter the total Number of Rows : "))
columns = int(input("Please Enter the total Number of Columns : "))
print("Print Number Pattern - 1 and 0 in alternative Columns")
for i in range(1, rows + 1):
for j in range(1, columns + 1):
if(j % 2 != 0):
print('0', end = ' ')
else:
print('1', end = ' ')
print()
Python 输出交替列中的 0 和 1
Please Enter the total Number of Rows : 6
Please Enter the total Number of Columns : 9
Print Number Pattern - 1 and 0 in alternative Columns
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0