-1

I'm new to python and learning from a book can't seem to find the answer I'm looking for in the book or anywhere on google. maybe I'm just not wording my questions right.

So in the book it there is a simple tic-tac-toe game. the if statement is written like this....

if theBoard[move] == ' ':

theBoard is a dictionary and move is an input. I'm wondering what does it mean when two variables sit together like that and one is inside a bracket.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

0

You're going to need to access the dictionary to use it right? The square brackets say that the value of move is associated to another value in the dictionary. The code is saying that if the value in the dictionary associated to the value of move in the dictionary is a space, then execute some code. You're going to see this square bracket notation A LOOOOOOTTTTTT for the rest of your life, so I would really drill this.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

For dictionary it mean get element from the dictionary.

dictionary = {
  'item_1': '...',
  'item_2': '1',
  'item_3': 2,
}

dictionary['item_1'] # you can get item_1 from dictionary like this

# or this
item_name = 'item_1'
dictionary[item_name]

For a list, you can use index to get the item store in it.

  obj = object()
  li = [1, '2', obj, ]
  
  # slicing operation in list
  li[0]   # get the 1st item.
  li[-1]  # get the last item.
  li[1:3] # get item from index 1 to 3 not include index 1.
  li[:]   # get all item. it can use to copy the list.
kamho
  • 16
  • 5
0

It seems like you're looking at this tic-tac-toe game.

As you mentioned, theBoard is a dictionary, here is it's initial condition:

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
            '4': ' ' , '5': ' ' , '6': ' ' ,
            '1': ' ' , '2': ' ' , '3': ' ' }

In Python dictionaries have 'keys' and 'values' (follow the link to learn more). In this case the keys are the numbers 1-9 and, initially at least, they are all equal to ' '.

Appending [key] to the name of the dictionary extracts that key's value.

For example:

# define the dict
dictionary = {'key1':'value1', 'key2':'value2'} 
# extract value2
dictionary['key2']

In your example move is the key, and is being used to check whether the value is ' ' or not.

As mentioned above, similar syntax occurs throughout Python. It's worth reviewing the data structures documentation to solidify concepts.

Arthur Morris
  • 1,253
  • 1
  • 15
  • 21