Battleship Board


board = []

for x in range(0,5):
board.append(["O"] * 5)

def print_board(board):
for row in board: *******?
print " ".join(row)

I have gotten through this exercise okay, but I do not understand why I am able to use 'row' in this code, as they have not been defined yet? How does Python know how to handle what a 'row' is? From what I can see, it is just assuming that it is five "O's", without being told that that is, what it in fact is.

I am probably just thinking about this wrong, but any clarification would be appreciated.


If you're referring to your for-loop, then part of a for-loop is to create a variable used to refer to each element in what you're iterating through

Whenever you post code, ensure that it's intact


Yes, as ionatan says, it has to do with how for-loops work, if I understand your question. This feature confused me a lot at first, too, so you aren't alone. :wink:

Basically, when you do a for-loop, you can call the element in the list anything you want, as long as your syntax is correct.

fruits = ["apple","pear","orange"] 
for fruit in fruits:
    print fruit

Of course, that makes sense. But I could also have written:

for basketballs in fruits:
    print basketballs


for i in fruit:
    print i

As long as you follow the proper syntax, the iterated element name you assign can be anything.
In fact Python doesn't 'understand' what a 'row' is.

I hope this helps!


@ionatan @joeb

Thanks guys. That helps alot.