## Introduction

A **Boolean** is a data type that has either one of two values representing a conceptual “true” or “false”. Booleans are named after the mathematician George Boole, who was a pioneer of mathematical logic. In programming, they are used for decision-making, (i.e. to determine whether the computer should do something or not.

## What is a Boolean?

In Python, Booleans are handled with the `bool`

type, which can hold one of two possible values: `True`

or `False`

. These values are case-sensitive and must be capitalized.

**Example:**

is_active = True is_logged_in = False

## Falsy and Truthy Values

Every value in Python has a Boolean equivalent. This means that any value can be used as or converted to a Boolean.

Data types and classes in Python can define which of their values is equivalent to `True`

or `False`

. In general, values that represent something empty or a kind of “nothing” get `False`

and other values within the type `True`

. For example, for `int`

types, `0`

is `False`

and any other `int`

is `True`

. For strings, an empty string `""`

is `False`

and any other string is `True`

.

### Falsy Values

Falsy values are those that evaluate to `False`

in a Boolean context. Common values that are falsy include:

`None`

`0`

(integer zero)`0.0`

(float zero)`''`

(empty string)`[]`

(empty list)`{}`

(empty dictionary)`set()`

(empty set)`False`

itself

### Truthy Values

Truthy values are all values that are not falsy. This includes all numbers except 0, non-empty strings, non-empty collections, and `True`

.

## The *bool()* Function

The `bool()`

function is used to convert a value to a Boolean. It returns `True`

if the value is truthy and `False`

if the value is falsy.

**Example:**

print(bool(42)) print(bool('Hello')) print(bool(None)) print(bool('')) print(bool([1,2,3]))

**Output:**

True True False False True

## Boolean Operators

Boolean operators perform logical operations on Boolean values. Since Python values have equivalent Booleans (i.e. they’re either truthy or falsy), in Python they can operate on any value. The primary Boolean operators in Python are `and`

, `or`

, and `not`

.

*and* Operator

The `and`

operator is similar to the logical ‘and’, which returns (evaluates to) true if two things are both true. The Python `and`

adds a twist to this, but let’s first see an example of how it works in the most basic way with Booleans.

**Example:**

print(True and True) print(True and False) print(False and False)

**Output:**

True False False

In the example above, line 1 has an `and`

that operates on two `True`

values, and therefore the result is `True`

. Line 2 has only one `True`

and line 3 has no `True`

values, and therefore both result are `False`

.

From the example above, it seems that the Python `and`

operates like the logical `and`

, which returns `True`

when both values are `True`

, and `False`

otherwise. However, what it’s actually doing is more subtle. The `and`

operator returns the value of the operand that has the final determination of the logical outcome.

To understand what that means, let’s look at an example with non-Boolean values.

**Example:**

print(1 and 2) print(2 and 1) print(3 and 0) print([] and 0) print(0 and [])

**Output:**

2 1 0 [] 0

On line 1 in the example above, given that the first operand is a `1`

, the value of the second operand determines the outcome of the logical operator. A falsy value of the second operand makes the entire expression logically false, and a truthy value there makes entire expression logically true. Therefore, in case both operands are truthy, the value that `and`

returns is the value of the second operand, which is `2`

in this case. You can see that `and`

indeed returns the value of the second operand when both are truthy, by looking at line 2, for which the returned value is `1`

.

Line 3 has one falsy value, and when that’s the case, that falsy value is always the one that makes the final determination, and is therefore the one that’s returned.

Lines 4 and 5 have two falsy values. When that’s the case, the first falsy value is the one that makes the determination because the expression is logically false regardless of the value of the second operand, and therefore the first falsy value is the one returned.

Here is a summary of what `and`

returns:

- If both values are truthy, the second value is returned.
- If one value is falsy and the other truthy, the falsy value is returned.
- If both values are falsy, the first falsy value is returned.

*or* Operator

The `or`

operator is similar to the logical ‘or’, which returns true if *at least* one value is true.

**Example:**

print(True or False) print(False or False) print(True or True)

**Output:**

True False True

The `or`

operator can, of course, operate on all truthy and falsy values as well, not just Booleans. Like the `and`

operator, `or`

also returns the value of the operand that has the final determination of the logical outcome.

**Example:**

print(1 or 2) print([] or 3) print(0 or [])

**Output:**

1 3 []

Here is a summary of what `or`

returns:

- If both values are truthy, the first value is returned.
- If one value is falsy and the other truthy, the truthy value is returned.
- If both values are falsy, the second falsy value is returned.

*not* Operator

The `not`

operator negates the Boolean value, returning `True`

if the operand is falsy, and `False`

if the operand is truthy. Unlike the `and`

and `or`

operators, `not`

always returns a proper Boolean, i.e. either `True`

or `False`

.

**Example:**

print(not True) print(not False) print(not 'Hello') print(not '') print(not 2) print(not 0)

**Output:**

False True False True False True

### Combining Boolean Operators

Boolean operators can be combined to create more complex logical expressions. For example, you can use parentheses to group operations and enforce a specific order of evaluation.

**Example:**

has_permission = is_admin or (is_logged_in and has_valid_token)

In the example above, the expression `(is_logged_in and has_valid_token)`

is evaluated first due to the parentheses. If it is `True`

, then the entire expression will be `True`

regardless of the value of `is_admin`

. If it is `False`

, then the value of `is_admin`

will determine the final result.

## Comparison Operators

Comparison operators are used to compare two values, and they return a Boolean result (`True`

or `False`

). The standard comparison operators in Python are:

`==`

(equal): Checks whether two values are equal.`!=`

(not equal): Checks whether two values are not equal.`>`

(greater than): Checks whether one value is greater than another.`<`

(less than): Checks whether one value is less than another.`>=`

(greater than or equal): Checks whether one value is greater than or equal to another.`<=`

(less than or equal): Checks whether one value is less than or equal to another.

**Examples:**

a = 10 b = 20 print(a == b) # --> False print(a != b) # --> True print(a > b) # --> False print(a < b) # --> True print(a >= b) # --> False print(a <= b) # --> True

**Output:**

False True False True False True

Every data type can define its own way of comparing its values, and some data types do not support all comparison operators.

The `complex`

type only supports the `==`

and `!=`

because complex numbers are not ordered.

Strings (`str`

types) support all comparison operators. They are compared in lexicographical order, character by character, from left to right.

**Example:**

print('apple' < 'banana') print('apple' == 'Apple')

**Output:**

True False

### Combining Comparison Operators

Comparison operators can be combined to test whether an expression is within a certain range. This is done by placing the expression between two comparison operators.

**Example:**

age = 25 is_age_allowed = 18 <= age <= 65

In the example above, the expression `18 <= age <= 65`

evaluates to `True`

if `age`

is between 18 and 65 (inclusive), and `False`

otherwise. The expression `18 <= age <= 65`

is effectively shorthand for `18 <= age and age <= 65`

, and as you can see, Boolean and comparison operators can also be used together.

## Short-Circuit Evaluation

Python uses short-circuit evaluation when evaluating Boolean expressions. This means that it will stop evaluating the operands of a Boolean expression as soon as the overall result is determined.

For the `and`

operator, if the first operand is falsy, the expression is immediately known as that, and the second operand is not evaluated. This is because a logical ‘and’ requires only one operand to be false for the whole expression to be false.

Similarly, for the `or`

operator, if the first operand is truthy, the expression is immediately evaluated as that, and the second operand is not evaluated. This is because a logical ‘or’ requires only one operand to be true for the whole expression to be true.

This short-circuit evaluation can be useful for preventing unnecessary computations and potential errors (e.g., dividing by zero) in complex Boolean expressions.

**Example:**

x, y = 1, 0 print(y != 0 and x/y) x, y = 1, 2 print(y != 0 and x/y)

**Output:**

False 0.5

In the example above, the `y != 0 and`

part of the expression guards against a division by zero. On line 2, the divisor, `y`

, is `0`

, and therefore `y != 0`

evaluates to `False`

. Because of short-circuit evaluation, that’s all the `and`

needs to determine its value, which is `False`

in this case. The division by 0 is not performed and no error occurs.

On line 5, `y`

is `2`

and therefore `y != 0`

evaluates to `True`

. The `and`

needs to evaluate the second operand to determine its value. The division is executed and the `and`

operator returns its result, `0.5`

.

## Naming Boolean Variables

When naming Boolean variables, it’s a good practice to use descriptive names that clearly indicate the condition or state being represented. This makes the code more readable and easier to understand.

Here are some guidelines for naming Boolean variables:

- Use a prefix like
`is_`

,`has_`

,`can_`

, or`should_`

to indicate the condition being checked. - Use clear and concise names that describe the condition.
- Avoid using negations like
`not_`

or`no_`

in the variable name, as this can make the code harder to read.

**Example:**

is_valid = True has_permission = False can_proceed = is_valid and has_permission

In the example above, the variable names `is_valid`

, `has_permission`

, and `can_proceed`

clearly describe the conditions they represent, making the code more self-documenting and easier to understand.

## Summary & Reference for Python Booleans

A Boolean in Python is a data type that represents one of two values: `True`

or `False`

. These values are case-sensitive and must be capitalized.

is_active = True is_logged_in = False

Booleans are useful in decision-making processes within your code, helping to determine the flow of execution based on conditions.

Every value in Python has a Boolean equivalent. Values that are equivalent to `False`

are called ‘falsy’ and values that are equivalent to `True`

are called ‘truthy’.

Data types and classes in Python can define which of their values is equivalent to `True`

or `False`

. In general, values that represent something empty or a kind of “nothing” get `False`

and other values within the type get `True`

.

Falsy values include: `None`

, `0`

, `0.0`

, `''`

(empty string), `[]`

(empty list), `{}`

(empty dictionary), `set()`

(empty set), and `False`

. Truthy values are all values that are not falsy, including non-zero numbers, non-empty strings, non-empty collections, and `True`

.

The `bool()`

function converts any value to its Boolean equivalent.

bool(42) # --> True bool(None) # --> False

Boolean operators (`and`

, `or`

, `not`

) perform logical operations. They can operate on any value and consider the Boolean equivalents. The `and`

and `or`

operators return the value of the operand that makes the final determination in the value of the logical expression. The `not`

operator returns the Boolean opposite of its operand.

print(1 and []) # --> [] print(1 or 2) # --> 1 print(not "") # --> True

Comparison operators (`==`

, `!=`

, `>`

, `<`

, `>=`

, `<=`

) return Boolean results based on the comparison of two values.

a = 10 b = 20 print(a == b) # False print(a < b) # True

Boolean expressions can be combined as well as use parentheses to enforce a specific order of evaluation.

is_admin = False is_logged_in = True has_valid_token = True has_permission = is_admin or (is_logged_in and has_valid_token) print(has_permission) # --> True

Python uses short-circuit evaluation for Boolean expressions. For `and`

, if the first operand is falsy, the second is not evaluated. For `or`

, if the first operand is truthy, the second is not evaluated.

x, y = 1, 0 print(y != 0 and x / y) # --> False

When naming Boolean variables, use descriptive names that clearly indicate the condition being represented, such as `is_valid`

, `has_permission`

, or `can_proceed`

.

is_valid = True has_permission = False can_proceed = is_valid and has_permission