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

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página