mercredi 7 juillet 2021

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

I have an assignment for my python course that im 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 im really new to coding.

I can produce a while loop that writes out the correct length and amount of lines but im 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?

Aucun commentaire:

Enregistrer un commentaire