Home > Mobile >  How can I arrange my grid into a variable?
How can I arrange my grid into a variable?

Time:05-04

So I wrote a code that yields a grid with the help of some helpful stackoverflow users, and here it is..

import random
import string

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

Now I want to store the grid in a variable x. I tried doing so like this..

import random
import string

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

but the output yields

[P][y][l][V]None
[c][U][f][m]None
[j][s][x][c]None
[G][v][R][X]None

How can I make the output only print out the letters without 'None' at the end of each line AS WELL AS store the grid in variable x?

CodePudding user response:

print() just prints its arguments, it doesn't return the string that it printed. So you're setting x to None.

Don't print the strings, concatenate them onto a variable.

import random
import string

result = ''

for x in range(4):
    for y in range(4):
        result  = f'[{random.choice(string.ascii_letters)}]'
    result  = '\n'

print(result)

CodePudding user response:

Check this out. Maybe using a numpy grid helps.

import string
import random
import numpy as np

grid = np.zeros((4,4), dtype=str)
for i in range(4):
    for j in range(4):
        grid[i,j] = random.choice(string.ascii_letters)
print(grid)
  • Related