Why do 'and' & 'or' return operands in Python?

后端 未结 4 1953
遇见更好的自我
遇见更好的自我 2020-11-30 14:42

I\'m going through the LPTHW and I came across something I cannot understand. When will it ever be the case that you want your boolean and or or to

4条回答
  •  抹茶落季
    2020-11-30 15:27

    Consider the following use case:

    element = dict.has_key('foo') and dict['foo']
    

    Will set element to dict['foo'] if it exists, otherwise False. This is useful when writing a function to return a value or False on failure.

    A further use case with or

    print element or 'Not found!'
    

    Putting these two lines together would print out dict['foo'] if it exists, otherwise it will print 'Not found!' (I use str() otherwise the or fails when element is 0 (or False) because that s considered falsey and since we are only printing it doesn't matter)

    This can be simplified to

    print dict.has_key('foo') and str(dict['foo']) or 'Not found!'
    

    And is functionally equivalent to:

    if dict.has_key('foo'):
        print dict['foo']
    else:
        print 'Not found!'
    

提交回复
热议问题