Having problems understanding 2 things in the code below. Problem 1: I dont understand what is themap and what is it's use. Usually when we create functions with 2 arguments like here :
def find_city(themap,state): shouldn't we enter the value of the 2 arguments
themap and state when we run the program? And yet, we only give the values of state
i.e we enter either CA OR MI OR FL . I dont understand what is themap being used for.
Problem 2 : I dont understand the line cities['_find'] = find_city
I searched google for '_find' python and the only thing I found was reference to zed shaw's book. which category does it come under or what should I read to learn more about this line?
cities = {'CA': 'San Francisco', 'MI': 'Detroit',
'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
EDIT: Could you also tell me which chapter or python topic should I study to be able to understand this better. I mean, to better understand about the questions that I asked.
cities['_find'] = find_cityis way to reference find_city function, hence this dictionary element is a function, to call it just reference the element then add arguments:cities['_find'](cities, state), it's just another way to call find_city function.themapcomes from the function call:city_found = cities['_find'](cities, state), i.e. the dictionarycitiesis passed as the first argument offind_citymethod and copies intothemap, so no need to takethemapfrom user. Problem 2:'_find'here is not a keyword and has been used just as an indexing value for thedictobjectcities... it could have been anything (e.g.'find','_search','locate'etc).cities['_find'] = find_cityis a terrible idea. Now if someone tried to find a city called"_find"they will be returned a function instead of the message"Not found."