Booleans

In this tutorial, we'll cover the fundamentals of booleans, including boolean literals and variables, logical operators, truthiness and falsiness, and short-circuit evaluation. Let's dive in!

Introduction to Booleans

A boolean is a data type that can represent one of two values: True or False. Booleans are commonly used in programming to represent the outcome of comparisons, control the flow of a program, or check conditions.

Boolean Literals and Variables

In Python, you can create boolean variables by assigning the True or False values directly to a variable:

is_active = True
is_admin = False

You can check the data type of a variable using the type() function:

print(type(is_active))  # Output: <class 'bool'>

Logical Operators

Python provides three logical operators to combine boolean values:

  • and: Returns True if both operands are True, otherwise False.
  • or: Returns True if at least one of the operands is True, otherwise False.
  • not: Returns True if the operand is False, and False if the operand is True.

Here are some examples:

a = True
b = False

print(a and b)  # Output: False
print(a or b)   # Output: True
print(not a)    # Output: False

Truthiness and Falsiness

In Python, non-boolean values can be treated as booleans in a context where a boolean is expected, like in a conditional statement. These values are said to be "truthy" or "falsy":

  • Truthy values: Non-zero numbers, non-empty strings, non-empty lists, and other non-empty data structures evaluate to True.
  • Falsy values: Zero, empty strings, empty lists, None, and other empty or null data structures evaluate to False.

The bool() function can be used to convert values to their boolean equivalents:

print(bool(42))         # Output: True
print(bool(-3.14))      # Output: True
print(bool(""))         # Output: False
print(bool([1, 2, 3]))  # Output: True
print(bool(None))       # Output: False

Short-Circuit Evaluation

Python uses short-circuit evaluation when evaluating logical expressions. This means that as soon as the outcome of an expression is determined, the remaining parts of the expression are not evaluated. This can lead to performance benefits, as well as some pitfalls to watch out for.

Here's an example:

def truthy_function():
    print("Truthy function called!")
    return True

def falsy_function():
    print("Falsy function called!")
    return False

result = truthy_function() or falsy_function()

In this case, only "Truthy function called!" will be printed because the or expression short-circuits as soon as it encounters a truthy value.

Keep in mind that short-circuit evaluation can lead to unexpected behavior if the unevaluated parts of the expression have side effects or if you rely on all parts of the expression being evaluated.