Search code examples
pythonloopsprintingnestednested-loops

How do I have something be "skipped" over on the last iteration?


So I creating the simple small project of Tic Tac Toe in python

Tic Tac Toe board in text with a, b, and c identifying columns and 0, 1, and 2 identifying rows

(Same board in text form):

     a   b   c

0    - | - | -

    -----------
1    - | - | -

    -----------
2    - | - | -

When I try to do this with just loops I get artifacts like "|" at end of rows and "---------" below row 2 when it's only supposed to be below rows 0 and 1. I was able to circumvent this with if statements, but I wonder if there is a better way.

I originally had

def print_board():
    print("     a   b   c")
    print("")
    print("0    " + coords[columns[0]][rows[0]] + " | " + coords[columns[1]][rows[0]] + " | " + coords[columns[2]][rows[0]])
    print("   -------------")
    print("1    " + coords[columns[0]][rows[1]] + " | " + coords[columns[1]][rows[1]] + " | " + coords[columns[2]][rows[1]])
    print("   -------------")
    print("2    " + coords[columns[0]][rows[2]] + " | " + coords[columns[1]][rows[2]] + " | " + coords[columns[2]][rows[2]])

This is the best design for this I could come up with, and it works.

def print_board():
    print("     a   b   c", end="\n\n")
    for r in range(3):
        print(str(r) + "    ", end="")
        for c in range(3):
            print(coords[columns[c]][rows[r]], end="")
            if c != 2:
                print(" | ", end="")
        print("\n")
        if r != 2:
            print("   -------------")

However, I feel like this could be better. Specifically I want to get rid of the if statements but get the same result. So I am wondering if I can skip parts of a loop on the last iteration?


Solution

  • You can use the join function (https://docs.python.org/3/library/stdtypes.html#str.join) to insert separators only between the elements of a list, in this way you can avoid all the if statements:

    def print_board():
        print("     a   b   c", end="\n\n")
        rows = [0, 1, 2]
        columns = ["a", "b", "c"]
    
        rows_formatted = []
        for r in rows:
            row_elements = []
            for c in columns:
                row_elements.append(coords[c][r])
            rows_formatted.append(f"{r}    {' | '.join(row_elements)}\n")
        print("   -------------\n".join(rows_formatted))
    
    # Example usage:
    coords = {
        "a": ["X", "O", "X"],
        "b": ["O", "X", "O"],
        "c": ["X", "O", "X"]
    }
    
    print_board()
    

    Example output:

         a   b   c
    
    0    X | O | X
       -------------
    1    O | X | O
       -------------
    2    X | O | X