Python循环函数参数

时间:2018-02-14 22:35:42

标签: python function arguments

我是新手,刚开始从codeacademy学习Python。在下面的函数中,我无法理解为什么print_board函数使用参数board_in但是board_in根本没有被引用?

board = []

for i in range(5):
  board.append(["O"] * 5)

def print_board(board_in):
  for row in board:
    print row

print_board(board)

1 个答案:

答案 0 :(得分:2)

board_in参数完全未使用。您发现了错误的代码,或许意味着使用该参数,但有人犯了错误并忘记使用它。

函数体使用全局名称board(同样的名称也作为函数调用的参数传入)。这就是代码恰好起作用的原因,但是当你传递完全不同的东西时 不会按预期工作:

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

当您传递完全不同的内容时,它会继续打印board列表,例如print_board(None)。在调用函数(并传入其他内容)之前使用NameError时,它将失败del board

>>> 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

我怀疑预期的实现是:

def print_board(board_in):
    for row in board_in:
        print row

现在正在使用board_in