Learn Python by Building Data Science Applications
上QQ阅读APP看书,第一时间看更新

Logical operators

There are four logical operators that work specifically on Boolean values:

  • !—the NOT keyword (inverse of the resulting value):
>>> not (5 > 4)
False
Jupyter interprets cells with an exclamation mark at the beginning as Terminal commands, so we can't use it there.
  • |—the OR keyword (one or another, or both the values):
>>> (5 > 4) | (6 < 5)
True
  • &—the AND keyword (one and another value):
>>> (5 > 4) & (6 < 5)
False
  • ^—the XOR keyword (either one or another, but not both of the values):
>>> (5 > 4) ^ (5 < 6)
False

The following are built-in functions that work on Boolean arrays:

  • all(): Will return true only if all elements are True
  • any(): Will return true if at least one element is True
Python has strong typing—it does not convert data types implicitly. The only exception is tests for True/ False: any data type will work as a Boolean in any test, following these general rules:  While using variables like that in tests looks nice, be careful;  it often introduces bugs, for example, if  you mean variable to be  None  in the tests, but it was returned as an empty string. If  you're not sure, better check for a specific value.

Zero (both float and int), empty string, and None behave in tests as False. Anything else behaves as True. Consider this example:
>>> not ''
True
>>> bool('')
False

We will cover working with arrays and other structures in Chapter 4, Data Structures.