How can I make my code return random letters in a grid?

407 views Asked by At

I'm trying to write a code that will return random letters in a 4 * 4 grid. Here is my attempt so far

So I have created a grid like this

[][][][]
[][][][]
[][][][]
[][][][]

using this code:

board = ['[]' * 4 ] * 4
for x in board:
    print(x)

and now I'm trying to replace each [] with a letter in it, like [A]

and I tried to do it by implementing this piece of code

import random
import string
for x in row:
    print(random.choice(string.ascii_letters))

but the code prints this out..

s
K
U
J
l
e
X
s

instead of a grid, which I expected to be like this...

[A][D][F][T]
[S][D][A][E]
[R][V][B][S]
[O][P][L][K]

what should I change in my code to ensure the output is like the grid mentioned right above?

Here is my full code btw..

import random
import string

board = ['[]' * 4 ] * 4
for row in board:
    print(row)

for x in row:
    print(random.choice(string.ascii_letters))
2

There are 2 answers

0
Tim Roberts On

Like this:

import random
import string

for x in range(4):
    for y in range(4):
        print( '['+random.choice(string.ascii_letters)+']',end='' )
    print()

Output:

[I][j][p][r]
[O][C][H][x]
[y][a][e][x]
[V][z][Y][r]
0
Oghli On

You could do it in this way:

board = []
row = []
for i in range(4):
    row.clear()
    for j in range(4):
        row.append('[' + random.choice(string.ascii_letters) + ']')
    board.append(row.copy())

for row in board:
    print(''.join(row))

Output:

[Q][E][v][Z]
[w][w][Q][R]
[R][l][c][J]
[p][F][S][M]

Process finished with exit code 0