Writing a "Chessboard" function in Python that prints out requested length of binary

Question:

I have an assignment for my Python course that I’m struggling with.

We are supposed to make a function that prints out binary as follows:

If the input is:

chessboard(3)

It should print out:

101
010
101

And so forth..

Its a "simple" program but I’m really new to coding.

I can produce a while loop that writes out the correct length and amount of lines but I’m struggling to produce variation between the lines.

This is what I have come up with so far:

def chessboard(n):
height = n
length = n
while height > 0:
    while length > 0:
        print("1", end="")
        length -= 1
        if length > 0:
            print("0", end="")
            length -= 1
    height -= 1
    if length == 0:
        break
    else:
        print()
        length = n

With the input:

chessboard(3)

It prints out:

101
101
101

Could someone help me figure out how I could start every other line with zero instead of one?

Asked By: sc0rched

||

Answers:

As I understand it, it is simple :

print("stackoverflow")

def chessboard(n):
    finalSentence1 = ""
    finalSentence2 = ""
    for i in range(n): #we add 0 and 1 as much as we have n
        if i%2 == 0: #
            finalSentence1 += "1"
            finalSentence2 += "0"
        else:
            finalSentence1 += "0"
            finalSentence2 += "1"


    for i in range(n): #we print as much as we have n
        if i%2 == 0:
            print(finalSentence1)
        else:
            print(finalSentence2)



chessboard(3)

returns :

stackoverflow
101
010
101
Answered By: Gaston

I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:

def chessboard(size):

 output_1 = ''
 output_2 = ''
 i = 1
 j = 1

 while j <= size:

   while i <= size:
        
        if i % 2 == 0:
            output_1 += '1'
            output_2 += '0'
            i += 1
        else:
            output_1 += '0'
            output_2 += '1'
            i += 1

    if j % 2 == 0:
        print(output_1)
        j += 1
    else:
        print(output_2)
        j += 1

chessboard(5)

returns:

10101
01010
10101
01010
10101
Answered By: Tiia Makinen
def chessboard(x):
    i = 0
    while i < x:
        if i % 2 == 0:
            row = "10"*x
        else:
            row = "01"*x
        print(row[0:x])
        i += 1
Answered By: RookieMistake
def chessboard(n):
    board = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append('1' if (i+j)%2 == 0 else '0')
        board.append(row)
    return 'n'.join(''.join(row) for row in board)

print(chessboard(3))

Output

101
010
101
Answered By: nrgx