Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

write python code to print a square grid

  1. User

    write python code to print a square grid

  2. Assistant

    Certainly! Here's a code snippet in Python to print a square grid:

    def print_grid(n):
        for i in range(n):
            print('+', end=' ')
            for j in range(n):
                print('- ', end='')
            print('+', end='\n')
            
            for k in range(n):
                print('|', end=' ')
                for l in range(n):
                    print('  ', end='')
                print('|', end='\n')
    
        print('+', end=' ')
        for m in range(n):
            print('- ', end='')
        print('+')
    
    # Testing the function with a square grid of size 5
    print_grid(5)
    

    This code defines a function print_grid that takes an integer n as input, which denotes the number of rows and columns in the square grid. It uses nested loops to draw the grid, alternating between printing horizontal lines and vertical lines. The grid is enclosed by + symbols, and the horizontal lines are represented by - characters, while the vertical lines are represented by | characters.

  3. User

    write python code to draw a square checkerboard pattern

  4. Assistant

    Certainly! Here's a code snippet in Python to draw a square checkerboard pattern:

    def draw_checkerboard(n):
        for i in range(n):
            for j in range(n):
                if (i+j) % 2 == 0:
                    print('# ', end='')
                else:
                    print('  ', end='')
            print()
    
    # Testing the function with a checkerboard pattern of size 8
    draw_checkerboard(8)
    

    In this code, we define a function draw_checkerboard that takes an integer n as input. It uses nested loops to iterate through each cell of the checkerboard. The condition (i+j) % 2 == 0 checks if the sum of the row index and column index is even, if so it prints a # (black square), otherwise it prints two spaces ( ) representing an empty cell.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.