2016-11-04 9 views
0

ネストされたif/elseステートメントで問題が発生しています。ifステートメントがtrueを評価しても、部分一致以上のelseステートメントが実行されます。なぜ起こるのかわかりません。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

「同一性のテスト」です。両方のオブジェクトが同じかどうかをチェックします。明らかに、 'filter'の戻り値はオブジェクト' True'を返しません。あなたは '=='演算子を使いたいとします。この場合は完全に省略し、 'if exactMatch:'と書くだけです。 –

答えて

4

bool(exactMatch)exactMatchは、厳密にTrueであることを意味するものではありませんTrueです。 Pythonで

オブジェクトは、彼らがブール値でない場合でも、ブール値のコンテキストでtruthyfalsyかもしれません。例えば

:あなたはIDチェックをスキップし、共通のPythonのイディオムについては

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

。たとえば、

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. 
関連する問題