Boolean

Revision as of 21:39, 10 March 2011 by Smitschu (talk | contribs) (updated and extended for the introduction to programming course)

Boolean logic, named after George Boole, is a complete system of logical operations. A boolean is a primitive datatype in almost all programming languages that can represent the values true and false in logical expressions. They are used primarily in conditional tests. In Python the test in the first line of an if statement or while loop must evaluate to a boolean, and the reserved words True and False (note the capitalization) are constants representing the two possible values of a boolean.

All the relational operators return booleans.

Boolean Operations

  • x and y will return true iff both x and y are true.
  • x or y will return true iff either x or y is true (or both).
  • not x will return true iff x is false (i.e. it negates x).

Operations can be chained, and if necessary precedence can be forced with parentheses. For example,

(x and not y) or (z and not y)

will return true iff y is false and at least one of x and z are true.

Also note that and and or are short-circuit operators. This means that if the value of the first operand is sufficient to determine the result, the second is never evaluated. That is, if the first operand of an and statement is false, or if the first operand of an or statement is true, the second operand won't be checked. For example,

(5 in myList) and (myList.index(5) < 3)

will never give an error, because if 5 isn't in myList the second half of the statement will never be evaluated (normally, if you called index for something that isn't in a list you'd get an error, but that can never happen in this statement because in that case it would short-circuit).