Python Boolean Data Type

What is a Boolean?

In Python, a boolean is a built-in data type that can hold one of two values: True or False. These values represent truth values, and are commonly used in conditional statements, loops, and logical operations.

Boolean Values

Boolean Type and Truthiness

Python treats several values as falsy, meaning they evaluate to False when converted to boolean:

All other values are considered truthy (evaluate to True).

Using Boolean Values

a = True
b = False

if a:
    print("a is True")

if not b:
    print("b is False")

Boolean Operations

Python supports logical operators to combine boolean expressions:

x = True
y = False

print(x and y)  # Output: False
print(x or y)   # Output: True
print(not x)    # Output: False

Boolean Conversion

Use the bool() function to convert any value to its boolean equivalent.

print(bool(0))        # False
print(bool(42))       # True
print(bool(""))       # False
print(bool("Python")) # True

Best Practices with Booleans

Example: Simple Login Check

username = "user1"
password = "password123"

def check_login(user, pwd):
    is_authenticated = (user == "user1") and (pwd == "password123")
    return is_authenticated

if check_login(username, password):
    print("Login successful!")
else:
    print("Login failed.")