First, if you learn Python, stick with PEP8 conventions: here, you should use snake_case
variables names instead of CamelCase
names (see: https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles). Now, let me rewrite the code snippet:
def print_board(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
if __name__ == "__main__":
the_board = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':'X', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
print_board(the_board)
You have two different parts: 1. the function definition ; 2. the main part of the program.
The if __name__ == "__main__":
is not mandatory, but marks the block as the entry point of the program. Have a look at the function signature (what's after the def
keyword): you have the name if the function (print_board
) and, between parentheses, the parameters (here: on parameter named board
).Try to think of the body of the function as a block that knows the values of its parameters and nothing else (this behaviour can be different if you play with scopes, see @tchainzzz's answer). The body of the function uses its parameter to print a board.
The counterpart is: when you call a function, you have to give this function the parameters it expects, because the function knows nothing else. Here, the_board
is the value of the parameter on the print_board
function call. But try to pass another value:
>>> print_board({'top-L': ' ', 'top-M': ' ', 'top-R': 'XYZ', 'mid-L': ' ', 'mid-M':' ', 'mid-R': 'TUV', 'low-L': ' ', 'low-M': ' ', 'low-R': 'ABC'})
| |XYZ
-+-+-
| |TUV
-+-+-
| |ABC
Or no value:
>>> print_board()
Traceback (most recent call last):
...
TypeError: print_board() missing 1 required positional argument: 'board'
Or two values:
>>> print_board(the_board, 2)
Traceback (most recent call last):
...
TypeError: print_board() takes 1 positional argument but 2 were given
Or a totally different value:
>>> print_board(0)
Traceback (most recent call last):
...
TypeError: 'int' object is not subscriptable
>>> print_board([])
Traceback (most recent call last):
...
TypeError: list indices must be integers or slices, not str
I hope you get it! These scopes are here to help you understand what's going on in your program. You don't have to read two thousands lines of code to find the place where board
was defined: when you read the function, you assume it was defined somewhere and that's all.
theBoard
passed to function is calledboard
inside function. The argumentboard
receives the value oftheBoard
.def printabc(): print('abc') printabc()
2) Could we use "theBoard" instead of replacing it with another argument known as "board"? Why?