Python Booleans

Boolean Values and Expressions

Booleans are used to evaluate expressions and determine whether they are true or false. In Python, any expression that compares values will result in a Boolean answer. For example:

print(15 > 12)  # Output: True
print(15 == 12)  # Output: False
print(15 < 12)  # Output: False

Using Booleans in Conditional Statements

When used in if statements, Boolean values determine the flow of execution. Python evaluates the condition and executes the corresponding block of code based on whether the condition is **True** or **False**. For example:

a = 150
b = 75
if b > a:
print("b is greater than a")
else:
print("b is not greater than a") # Output: b is not greater than a

Evaluating Values and Variables

The bool() function can be used to convert values into their Boolean equivalents. Here’s how you can evaluate various types of values:

print(bool("The Catcher in the Rye"))  # Output: True
print(bool(29.99))  # Output: True

Additionally, you can evaluate variables:

x = "To Kill a Mockingbird"
y = 18.50

print(bool(x))  # Output: True
print(bool(y))  # Output: True

Truthy and Falsy Values

In Python, most values evaluate to **True** if they contain some content:

print(bool("War and Peace"))  # Output: True
print(bool(12.99))  # Output: True
print(bool(["Pride and Prejudice", "1984", "Moby Dick"]))  # Output: True

However, certain values are considered False, including:

print(bool(False))  # Output: False
print(bool(None))  # Output: False
print(bool(0))  # Output: False
print(bool(""))  # Output: False
print(bool(()))  # Output: False
print(bool([]))  # Output: False
print(bool({}))  # Output: False

Additionally, custom objects can be made to evaluate as False if their len method returns 0:

class MyBookshelf:
    def __len__(self):
        return 0

my_books = MyBookshelf()
print(bool(my_books))  # Output: False

Boolean Functions

You can define functions that return Boolean values. For example:

def is_book_available():
    return True
print(is_book_available()) # Output: True

Based on the Boolean result from a function, you can control the flow of your program:

def is_book_available():
    return True

if is_book_available():
    print("The book is available!")
else:
    print("The book is not available.")  # Output: The book is available!

Python also includes many built-in functions that return Boolean values. For instance, isinstance() checks if an object is of a particular type:

price = 19.99
print(isinstance(price, float))  # Output: True

For more information, refer to the official documentation on Boolean values, isinstance(), and functions.

Leave a Comment

Your home address.