Home > Mobile >  How to make my number board start at 1 end at 9 and arrange itself in 3 rows
How to make my number board start at 1 end at 9 and arrange itself in 3 rows

Time:10-30

I'm trying to understand this code from "12 Beginner Python Projects - Coding Course" on the FreeCodeCamp Youtube channel and I really don't understand this code to print a board for the Tic Tac Toe project. I've looked around on some other vids and I didn't like how they set up their board. My first idea on how to solve this before I watched the vid fell through so I went with her code on how to generate the board but I don't actually understand what its doing.

Using the code:

number_board = [[str(i) for i in range(j*3, (j 1)*3)] for j in range(3)]
for row in number_board:
    print('['   ']['.join(row)   ']')

has the output:

[0][1][2]
[3][4][5]
[6][7][8]

I want it the output to be basically the same except starting at 1 and ending at 9 and the part I don't understand is: (j*3, (j 1)*3)] for j in range(3)

I understand that the final range(3) dictates how many rows there are and if I change that to 5, it would be 5 rows and go up to 14. I thought I understood the "start: stop: step" concept but when I alter the start to be (j*3 1, (j 1)*3)] the output is:

[1][2]
[4][5]
[7][8]

Which I think is due to the stop not adding up to 10 but If I change it to something like [[str(i) for i in range(j*3 1, 10)] for j in range(3)] it starts at 1 but doesn't end where I want it to. I tried a bunch of different combinations to get what I want but even if I guessed the correct one I still wouldn't know why it works.

[1][2][3][4][5][6][7][8][9]
[4][5][6][7][8][9]
[7][8][9]

Maybe I'm missing something really obvious since this is my first month of learning so my apologies if this is an obvious question but I just don't understand how the start: stop: step modifiers work(not even sure if they're called modifiers or what the proper name for them is)

CodePudding user response:

This style of loops are called list comprehensions in python. Do a short search and you will get lots of information about them. What happens in your code is practically same with the following:

number_board = []
for j in range(3):
    board_row = []
    for i in range(j*3, (j 1)*3):
        board_row.append(str(i))
    number_board.append(board_row)

for row in number_board:
    print('['   ']['.join(row)   ']')

So first code iterates over 3 rows For each row it needs to generate 3 numbers. This numbers are decided by range(j*3, (j 1)*3). So

  • when j=0, numbers are between 0 and 3
  • when j=1, numbers are between 3 and 6

Please check out python range documentation As stated in documentation, format for range is range(start, stop, step)

Once the board is created, it is printed out with another for loop

  • Related