2016-11-04 33 views
0

我在嵌套的if/else語句中遇到了一些麻煩。上面的部分匹配的else語句即使在if語句的結果爲true時也會執行。我看不出爲什麼會發生這種情況..任何幫助都將不勝感激。嵌套if/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) 
+3

'is'測試身份。它檢查兩個對象是否相同,並且顯然'filter'的返回不會返回對象'True'。你想使用'=='運算符,或者在這種情況下,只是完全省略它,只是寫'如果exactMatch:' –

回答

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.