Skip to content

Python Boolean

Boolean logic is a fundamental concept in programming that deals with truth values: True and False. In Python, the bool data type is used to represent Boolean values, and Boolean logic plays a crucial role in decision-making, flow control, and creating conditions for executing code. In this comprehensive guide, we’ll explore Boolean values, logical operators, and their applications in Python programming.

In Python, the two Boolean values are True and False. They represent the binary concept of truth and falsehood, and they are the building blocks for logical operations.

booleans.py
is_python_fun = True
is_learning = False

Here, is_python_fun is assigned the value True, indicating that the statement “Python is fun” is true. Similarly, is_learning is assigned False, indicating that the statement “I am learning Python” is false.

Logical operators in Python are used to perform operations on Boolean values. The three primary logical operators are and, or, and not.

Diagram:

diagram logical operators mermaid
Truth outcomes for and, or, not

The full truth table for and and or:

aba and ba or b
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

The and operator returns True if both operands are true; otherwise, it returns False.

booleans.py
x = True
y = False
result = x and y
print(result)

Output:

command
C:\Users\Your Name> python booleans.py
False

The or operator returns True if at least one of the operands is true; otherwise, it returns False.

booleans.py
x = True
y = False
result = x or y
print(result)

Output:

command
C:\Users\Your Name> python booleans.py
True

The not operator returns the opposite of the operand. If the operand is True, not returns False; if the operand is False, not returns True.

booleans.py
x = True
result = not x 
print(result)

Output:

command
C:\Users\Your Name> python booleans.py
False

Python stops evaluating a logical expression as soon as the result is known. With and, if the first operand is falsy the second is never checked; with or, if the first is truthy the second is skipped. This is called short-circuiting.

short_circuit.py
def expensive():
    print("expensive() was called")
    return True
 
False and expensive()   # expensive() is NEVER called
True or expensive()     # expensive() is NEVER called

A practical use is guarding against errors — the right side runs only when it is safe:

guard.py
name = ""
if name and name[0] == "A":   # name[0] only runs if name is non-empty
    print("Starts with A")

and / or Return Operands, Not Just Booleans

Section titled “and / or Return Operands, Not Just Booleans”

A subtle but useful fact: and and or return one of the actual operands, not necessarily True/False. or returns the first truthy value; and returns the first falsy value (or the last operand).

operands.py
print("" or "default")    # default   -> first truthy value
print("Alice" or "guest") # Alice     -> first truthy value
print(5 and 0 and 9)      # 0         -> first falsy value

This powers the common “default value” idiom: username = entered_name or "Anonymous".

Comparison operators are used to compare values and return Boolean results. These operators include == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).

booleans.py
a = 5
b = 10
result = a < b 
print(result)

Output:

command
C:\Users\Your Name> python booleans.py
True

Boolean values are frequently used in conditional statements, such as if, elif (else if), and else, to control the flow of a program based on certain conditions.

booleans.py
temperature = 25
 
if temperature > 30:
    print("It's a hot day!")
elif 20 <= temperature <= 30:
    print("It's a pleasant day.")
else:
    print("It's a cold day.")

Output:

command
C:\Users\Your Name> python booleans.py
It's a pleasant day.

In this example, the program checks the temperature and prints a message based on whether it’s hot, pleasant, or cold.

Functions can also return Boolean values, making them versatile for various programming tasks. For example, a function can check if a number is even and return True or False accordingly.

booleans.py
def is_even(number):
    return number % 2 == 0
 
result = is_even(10)
print(result)

Output:

command
C:\Users\Your Name> python booleans.py
True

Boolean values are frequently used in loop conditions. A while loop, for instance, continues executing as long as the condition is True.

booleans.py
count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1

Output:

command
C:\Users\Your Name> python booleans.py
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

In this example, the loop continues printing the count as long as it is less than 5.

In Python, you can cast other data types to Boolean values. The bool() function converts a value to a Boolean value, and it returns False if the value is empty, 0, or None; otherwise, it returns True.

booleans.py
print(bool("Hello"))  # True
print(bool(15))  # True
print(bool(["apple", "banana", "cherry"]))  # True

Output:

command
C:\Users\Your Name> python booleans.py
True
True
True

booleans.py
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))

Output:

command
C:\Users\Your Name> python booleans.py
False
False
False
False
False
False
False

Every Python object is either truthy or falsy when used in a boolean context (like an if). Only a small set of values are falsy; everything else is truthy.

Falsy valuesTruthy values
False, NoneAny non-zero number
0, 0.0, 0jAny non-empty string
"" (empty string)Any non-empty list/tuple/dict/set
[], (), {}, set()Most objects

This lets you write clean checks — if my_list: instead of if len(my_list) > 0:.

As noted earlier, bool is a subclass of int: True equals 1 and False equals 0. This means you can do arithmetic with them, which is handy for counting:

bool_int.py
votes = [True, False, True, True, False]
print(sum(votes))      # 3  -> counts how many are True
print(True + True)     # 2

Boolean logic is an integral part of Python programming, enabling developers to create conditions, make decisions, and control the flow of their code. Understanding Boolean values, logical operators, and their applications in conditional statements, functions, and loops is essential for writing clear, efficient, and effective Python code.


Exercise 1 – Boolean Values and Comparisons

Section titled “Exercise 1 – Boolean Values and Comparisons”

As you delve deeper into Python programming, continue exploring the intricacies of Boolean logic, and leverage its power to create dynamic and responsive programs. For additional insights and practical examples, check out our tutorials on Python Central Hub!

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading