【问题标题】:how can i write a python code for give row and column and print 10101 and 01010 pattern我如何编写一个 python 代码来给出行和列并打印 10101 和 01010 模式
【发布时间】:2022-01-20 09:53:27
【问题描述】:

我想编写一个 python 代码,用于从输入中给出行和列,并打印出像这张照片这样的模式:

我写了这段代码,但这只是显示 10101:

rows = int(input("Please Enter the total Number of Rows  : "))
columns = int(input("Please Enter the total Number of 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()

感谢您的关注...☺♥

【问题讨论】:

  • 您已经了解了如何识别备用列。使用相同的方法来识别备用行并以不同方式处理它们。
  • 请修改您发布的代码。缩进是代码的一部分。
  • 尝试在if条件中使用行列之和。 (请更正缩进)

标签: python python-3.x


【解决方案1】:

您需要同时考虑列索引和行索引以获得正确的解决方案。

rows = int(input("Please Enter the total Number of Rows  : "))
columns = int(input("Please Enter the total Number of Columns  : ")) 
for i in range(1, rows + 1):
    for j in range(1, columns + 1):
        if((j + i) % 2 == 1):          
            print('0', end = '  ')
        else:
            print('1', end = '  ')
    print()

或更短的版本

for i in range(1, rows + 1):
    for j in range(1, columns + 1):
            print((i + j + 1)%2, end = '  ')
    print()

【讨论】:

  • range(rows)range(columns) 更短:)
猜你喜欢
  • 2020-11-10
  • 2014-10-17
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多