Zorogx
Zorogx

Reputation: 33

Python - How to apply function to dictionary

I am a beginner for python and learning python from "Automate the Boring Stuff with Python".

I dont understand how a new function applies to dictionary in a tic-tac-toe board.

Thanks

  1. Why is it necessary to include the argument board in def printBoard(board)?

  2. Why do we need to add board before board['top-L']? I don't understand why does the function work as the previous line only define theBoard but not board.

theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':'X', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}

def printBoard(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'])
printBoard(theBoard)

Upvotes: 3

Views: 146

Answers (2)

jferard
jferard

Reputation: 8190

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.

Upvotes: 0

chang_trenton
chang_trenton

Reputation: 915

To answer your questions:

  1. We need to include the argument "board" in printBoard. Generally, dictionary "theBoard" is not guaranteed to be in scope (a.k.a. accessible) within the function. To make this code as general as possible, and allow it to print a dictionary in this general format, we need to pass the dictionary to be printed as a parameter to the function. However, if you wanted to import this function from a different file/module, you'd run into some problems: the function will not be able to find a variable called "theBoard." This is less clear in a language like Python, and if you replace the references to "board" to "theBoard" above, this will indeed work, since "theBoard" is in the global scope.

  2. In a similar vein, "board" within the function definition refers to whatever you passed in as a parameter. In this case, it's the dictionary theBoard. To see this, note that the function call printBoard(theBoard) is the actual line that does the printing. So imagine if every reference to parameter board in the body of the function definition was actually a reference to the dictionary theBoard.

In other words, I'd read up/practice the concept of scoping in programming languages, which I believe will make this example less confusing.

Upvotes: 3

Related Questions