Battleship - Printing Pretty


#1

I am not sure why the for loop for this lesson replaces the code from the previous section? It looks like CC is trying to show a command then how to make it better?

Previous Code:
def print_board(board):
for i in board:
print i

New Code:
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)


#2

your old code produces the following output:

['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']

the new code produces the following code:

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

looks much neater, right?


#3

Hi @stetim94,

What causes the code to look better with the following code? I am confused by this because I am trying to understand the code step by step.

def print_board(board):
    for i in board:
        print i
print_board(board)

I think I have asked you that before, sorry if its a repeat. Is there a way to have one command create both rows and columns?

Thanks again for all your help, I am very thankful. I signed up for the Udemy Python bootcamp course as a way to have further insight because CC doesn't seem to explain everything and I am planning on attending Iron Yard's Python bootcamp in July.


#4

compared to what? " ".join() converts the list into a string, which looks much more neat.

sorry, i don't understand? The code you show on the forum only prints, it doesn't "create". Command is not so commonly used, what do you mean by it?

Looking forward, you are going to give the user 3 guesses to guess your ship. This is why printing your board requires a function, so you can call the function to print an updated board after the user misses, otherwise, you would have to code printing the board every time, not very DRY


#5

print " ".join(row)
I tried running battleship on (Spyder) python 3.5.3 but i get the following error message "Definition : SyntaxError(...)

Type : Function of builtins module" on the line above. What does that mean. It works fine on codecademy tutorial. I apologise for the silly question. Any help/suggestion will be appreciated


#6

in python2 (codecademy) print is a statement, in python3 its a function call, so it requires parentheses


#7

@stetim94

Are there differences that require punctuation in 3 that is not in 2?


#8

parentheses are not punctuation? are they?


#9

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