YAL
YAL

Reputation: 691

What is the purpose of this if statement from "Learning Python the Hard Way"?

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
  1. I would like to know the purpose of this line since the code can run without an error even when I deleted this line.
  2. It seems like there's no condition that will ever make the program run this line, as I tried to put a print statement before break and it never got printed.

Upvotes: 3

Views: 109

Answers (1)

TigerhawkT3
TigerhawkT3

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

Related Questions