Reputation: 3
I'm new and just started learning Python from codeacademy. In the function below, I can't understand why the print_board function uses the argument board_in but board_in is not referred anywhere at all?
board = []
for i in range(5):
board.append(["O"] * 5)
def print_board(board_in):
for row in board:
print row
print_board(board)
Upvotes: 0
Views: 75
Reputation: 1121486
The board_in
paramater is completely unused. You have found bad code, that perhaps meant to use that parameter, but someone made an error and forgot to use it.
The function body instead uses the global name board
(the same name that is also passed in as an argument to the function call). This is why the code happens to work, but it won't work as intended when you pass in something completely different:
>>> print_board(None)
['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']
>>> print_board("This argument is ignored, so it doesn't matter what you pass in")
['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']
>>> board = [['A new value', 'for the board global'], ['means the output', 'changes']]
>>> print_board(2 + 2)
['A new value', 'for the board global']
['means the output', 'changes']
It'll continue to print the board
list when you pass in something completely different, like print_board(None)
. And it will fail with a NameError
when you use del board
before calling the function (and passing in something else):
>>> del board # remove the global altogether
>>> print_board({'foo', 'bar', 'baz'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in print_board
NameError: global name 'board' is not defined
I suspect that the intended implementation was:
def print_board(board_in):
for row in board_in:
print row
Now board_in
is actually being used.
Upvotes: 2