嵌套if / else,否则在应该执行时执行?

时间:2016-11-04 17:00:01

标签: python

我在使用嵌套的if / else语句时遇到了一些问题。即使if语句的计算结果为true,上面部分匹配的else语句也会执行..我不明白为什么会发生这种情况..任何帮助都将不胜感激

def search():
if request.method == 'GET':
    return render_template('search_form.html') # TODO ADD THIS TEMPLATE
elif request.method == 'POST':
    form = 'Search Form'
    searchInput = request.form['search']
    if len(searchInput) < 3:
        errStr = 'The search term you entered is to short. Searches must have 4 characters.'
        msg = [form, errStr]
        return error(msg)
    else:
        exactMatch = Clients.query.filter(or_(Clients.cellNum==searchInput,
                                          Clients.homeNum==searchInput,
                                          Clients.otherNum==searchInput)).first()
        print(exactMatch.firstName)
        print(bool(exactMatch))
        if exactMatch is True:
            clientID = exactMatch.id
            print(clientID)
        else:
            partialSearch = Clients.query.filter(or_(Clients.cellNum.like("%{}%".format(searchInput)),
                                         Clients.homeNum.like("%{}%".format(searchInput)),
                                         Clients.otherNum.like("%{}%".format(searchInput)),
                                         Clients.lastName.like("%{}%".format(searchInput)),
                                         Clients.firstName.like("%{}%".format(searchInput)))).all()
            return render_template('display_search.html', results=partialSearch)

1 个答案:

答案 0 :(得分:4)

bool(exactMatch) True并不意味着exactMatch严格True

Python中的对象在布尔上下文中可能是 truthy falsy ,即使它们不是布尔值。

例如:

bool("")  # False
"" is False  # False
bool("abc")  # True
"abc" is True  # False

对于常见的Python习语,您可以跳过身份检查。例如:

if exactMatch:
    do_something()
    # executes if exactMatch is thruthy in boolean context, including:
    # True, non-empty sequences, non-empty strings and almost all custom user classes
else:
    do_other_thing()
    # executes if exactMatch is falsy in boolean context, including:
    # False, None, empty sequences etc.