首页 > 解决方案 > python中的棋盘功能

问题描述

我正在尝试创建一个绘制棋盘的函数,但是当我放置偶数列时它不起作用

def board(rows,columns):
    for x in range(rows):
        if x%2 == 0:
            for y in range(1,columns+1):
                if y%2 == 1:
                    if y != columns:
                             print(" ",end="")
                    else:
                        print(" ")              
                else:
                    print("|",end="")
        else:
            print("-"*columns)
    print("True")

board(5,5)

标签: python

解决方案


Inaki,问题出在列中:

if y%2 ==1:
    if y != columns: # BTW you might think of y<columns 
        ...
    else:
        PRINT NEW LINE.  # <- you will never get here since y%2 == 1 but columns is even

您可能会喜欢这个解决方案(希望对您有所帮助!):

def board(rows,columns): 
    for x in range(rows*2-1):
        if x%2 == 0: 
            print(''.join([" |"]*columns)) 
        else: 
            print("--"*columns+"-") 

board(4,4) 

推荐阅读