Home > database >  Trouble printing each line of a string inside a double for loop python
Trouble printing each line of a string inside a double for loop python

Time:09-27

So I am working on my first terminal game in python as practice and I just can't get the output in the terminal to follow what I want.

Instance Variables:

board = []
board_size = 10
alphabet = "ABCDEFGHIJ"

Code snippet:

def create_board():
    for i in range(0, board_size):
        board.append(["."] * board_size)
        print_board(board)

def print_board(board):
    count = 0
    while count < 10:
        for i in board:
            board_layout = alphabet[count]   "  "   " ".join(i)
            continue
        count  = 1
    print(board_layout)

def main():
    create_board()

Terminal Output:

J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .
J  . . . . . . . . . .

The desired output should be A - J and with the dots at each letter. Please let me know what I should try.

Other attemps I've tried:

for letter in alphabet:
        for i in board:
            board_layout = letter   "  "   " ".join(i)
            continue
    print(board_layout)

for j in range(len(alphabet)):
        for i in board:
            board_layout = alphabet[j]   "  "   " ".join(i)
    print(board_layout)

I've also tried switching the order of the for loops with no success.

CodePudding user response:

How about doing it this way:-

BS = 10
ALPHA = 'ABCDEFGHIJ'
A = []

for c in ALPHA:
    A.append([c] ['.' for _ in range(BS)])
for r in A:
    print(*r)

CodePudding user response:

Try this out (short and simple):

board_size = 10
alphabet = "ABCDEFGHIJ"


dots = ' .' * board_size

for a in alphabet:
    print(f'{a} {dots}')

Explanation: when you multiply a string by a number, that string is repeated that amount of times. So 'a' * 3 becomes 'aaa' for example.

CodePudding user response:

try this :

>>> BS = 10
>>> ALPHA = 'ABCDEFGHIJ'
>>> print(*[c   ' .'*BS for c in ALPHA], sep='\n')
A . . . . . . . . . .
B . . . . . . . . . .
C . . . . . . . . . .
D . . . . . . . . . .
E . . . . . . . . . .
F . . . . . . . . . .
G . . . . . . . . . .
H . . . . . . . . . .
I . . . . . . . . . .
J . . . . . . . . . .
  • Related