Every decision a program makes comes down to a yes-or-no answer. Is the user logged in? Is the password long enough? Has the timer run out? Booleans are the data type that holds those answers. They are named after George Boole, a 19th-century mathematician who worked out an algebra of truth values long before computers existed.
You rarely type True or False by hand. More often a boolean is produced by a comparison such as age >= 18, then stored or used straight away in an if statement.
Example
age = 20
has_ticket = False
is_adult = age >= 18 # True
can_enter = is_adult and has_ticket # False
if not has_ticket:
print("Please buy a ticket first.")
Python capitalises True and False. JavaScript and Java write them in lowercase, and PHP accepts either case.
Combining true and false
Three logical operators do most of the work:
- and gives true only when both sides are true.
- or gives true when at least one side is true.
- not flips a value to its opposite.
JavaScript, Java and PHP usually spell these &&, || and !.
Truthy and falsy values
Here beginners often get caught out. Many languages let you put non-boolean values in a condition and quietly treat some of them as false. In Python, 0, an empty string "", an empty list and None all count as false. JavaScript has its own list, which includes NaN but treats an empty array [] as true. Java is strict and refuses to compile if (count) when count is an integer, so you must write if (count > 0).
One curiosity: Python's bool is a subclass of int, so True + True equals 2. That explains some odd results when booleans end up in arithmetic.
Where to go next
- Python course
- Test comparisons interactively in the Python editor
- See a loop that keeps running while a boolean stays true
Last updated