我已经对我的代码进行了三次检查,据我所知,它与本书中给出的ex40基本相同(LPTHW,Python 2.7):
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."
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
city_found = cities['_find'](cities, state)
print city_found
预期的输出是这样的:
State? (ENTER to quit) > CA
San Francisco
State? (ENTER to quit) > FL
Jacksonville
State? (ENTER to quit) > O
Not found.
State? (ENTER to quit) > OR
Portland
State? (ENTER to quit) > VT
Not found.
State? (ENTER to quit) >
但是当我运行它时,输入行只会重复,直到我在空白行上输入,从不生成一个城市。像这样:
State? (Enter to quit) > KS
State? (Enter to quit) > NY
State? (Enter to quit) > LA
State? (Enter to quit) > CA
State? (Enter to quit) >
Not found.
有人能告诉我我在俯瞰什么吗?
感谢。
答案 0 :(得分:1)
行
city_found = cities['_find'](cities, state) # Better: city_found = find_city(cities, state)
print city_found
需要在while
循环内,而不是在它之后。
我根本不明白cities['_find'] = find_city
的目的是什么 - 为什么不直接调用该函数而不是将其添加到城市字典中?对我来说似乎非常不合情理。