Reputation: 691
I am currently reading Learning Python the Hard Way and I have a question regarding one line of the following code.
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(">")
#This is the line I have question for
if not state: break
city_found = cities['_find'](cities, state)
print city_found
print
statement before break
and it never got printed.Upvotes: 3
Views: 109
Reputation: 49318
An empty string is considered a falsey value. Therefore, if not state:
means that the content of that block will be evaluated when state
is an empty string (or any other falsey value). The break
ends the loop early.
What this does is exit the loop immediately when the user simply presses Enter without entering any text.
Upvotes: 8