pythonfunctionif-statementwhile-loopbinary

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


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?


Solution

  • 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