Booleans
Feb 052018Boolean is a type of data, with only two possible values: true and false.
- In Python, the type
boolhas valuesTrueandFalse. - In Java, the type
booleanhas valuestrueandfalse.
Almost every programming language has Booleans, because they’re necessary for the checks, comparisons and other logical conditions in if/else statements and loops.(1)
Try the following in Python:
>>> 1 + 1 == 2
True
>>> 8000 > 9000
False
>>> 'Hello, world!'.startswith('Hello')
TrueTry the following in the BlueJ code pad:
>>> 1 + 1 == 2
true (boolean)
>>> 8000 > 9000
false (boolean)
>>> "Hello, world!".startsWith("Hello")
true (boolean)Many types, such as integers, strings and lists, have operations which result in Boolean values.
However, there are also operations on Booleans themselves; consider how a condition like x >= 0 and x <= 10 is evaluated:
- Suppose
xhas the value14. - The left hand side
x >= 0evaluates toTrue. - The right hand side
x <= 10evaluates toFalse. - So the condition simplifies to
True and False. - Since the left and right hand sides aren’t both
True, the result isFalse.
In particular, ‘and’ is a logical operation just like + is an arithmetic operation; it has input values and an output value, and the output is computed from the inputs.(2)
The other two standard logical operations are ‘or’ and ‘not’.(3)
- In Python, these operations are the keywords
and,orandnot. - In Java,
&&means ‘and’,||means ‘or’, and!means ‘not’.
Try the following in Python:
>>> True and False
False
>>> True or False
True
>>> not True
FalseTry the following in the BlueJ code pad:
>>> true && false
false (boolean)
>>> true || false
true (boolean)
>>> !true
false (boolean)Footnotes
- Some older, low-level or special purpose languages like C89 or MATLAB use the integer values
0and1rather than having a separate Boolean type. - Arithmetic operations have numeric inputs and numeric outputs; comparison operations have numeric inputs and Boolean outputs; logical operations have Boolean inputs and Boolean outputs.
- Since Booleans can only be true or false, the standard logical operations can be specified by truth tables giving their values in each possible case.
There are no published comments.