Battleship


#1

calling this:

for lst in range(0,5,1):
board.append(["O"] * 5 )
print board
results:

[['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

But calling this:

for i in range(0,5,1):
print (i)

results:

0
1
2
3
4

and calling this:
board = []
for lst in range(0,5,1):
board.append(["O"] * 5 )
def print_board(board):
for row in board:
print row

print print_board(board)

results:

['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']

. My point is in the first function why it outputs the five "O" 's from one to 5 and in all the other functions it outputs the standard five "O" 's five times. totally different from one.??


#2

in the 1st one it looks like you are printing the contents of the list "board" within your FOR loop, meaning it will print the whole "board" list. each time the loop happens, the list has grown and an updated "board" list is shown. in the 3rd one, your print statement is outside your initial FOR loop. your 2nd FOR loop is looping through "board" and printing each index within "board", which is why it shows up one line at a time.

they are the same thing, just printed in different ways.

board[0] --> ['O', 'O', 'O', 'O', 'O']
board[1] --> ['O', 'O', 'O', 'O', 'O']
board[2] --> ['O', 'O', 'O', 'O', 'O']
board[3] --> ['O', 'O', 'O', 'O', 'O']
board[4] --> ['O', 'O', 'O', 'O', 'O']


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.