Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 204
Zorogx Avatar asked Apr 16 '26 04:04

Zorogx


1 Answers

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.

like image 156
chang_trenton Avatar answered Apr 17 '26 21:04

chang_trenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!