Code:
NUM_SQUARES = 9
EMPTY = " "
def new_board():
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
Background:
I was reading this piece of code for the game 'Tic-Tac-Toe'. I don't understand the for loop in the function new_board()
.
My Understanding:
So in the first part of the code, I understand that there are two constants for: the number of squares on the board, an empty square on the board. In the function, an empty list is created where empty strings would be added to represent blank squares.
I understand that in range(NUM_SQUARES):
means that it will iterate the code below it 9 times. Therefore, it will add nine empty strings as items in the list.
What I don't get:
1) What is the square
variable assigned to?
2) What is the purpose of needing this variable square
?
3) Why do we commonly say i
in for i in range()
? (in general)