## Booleans

Feb 052018Boolean is a type of data, with only two possible values: *true* and *false*.

- In Python, the type
`bool`

has values`True`

and`False`

. - In Java, the type
`boolean`

has values`true`

and`false`

.

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')
True
```

Try 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
`x`

has the value`14`

. - The left hand side
`x >= 0`

evaluates to`True`

. - The right hand side
`x <= 10`

evaluates to`False`

. - So the condition simplifies to
`True and False`

. - Since the left and right hand sides aren’t both
`True`

, the result is`False`

.

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`

,`or`

and`not`

. - In Java,
`&&`

means ‘and’,`||`

means ‘or’, and`!`

means ‘not’.

Try the following in Python:

```
>>> True and False
False
>>> True or False
True
>>> not True
False
```

Try 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
`0`

and`1`

rather 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.