Python Boolean Data Type

The Boolean data type in Python represents one of two values: True or False. It is commonly used in conditional statements, comparisons, and logical operations.

Syntax

</>
Copy
bool_value = True  # A boolean variable with value True
bool_value = False # A boolean variable with value False

Boolean Values in Python

In Python, Boolean values are represented using the keywords True and False. These values are case-sensitive, meaning true and false (lowercase) will cause an error.

Boolean Type and Numeric Equivalence

Boolean values are internally represented as integers in Python: True is equivalent to 1, and False is equivalent to 0.

</>
Copy
print(int(True))  # Output: 1
print(int(False)) # Output: 0

Examples

1. Assigning Boolean Values

In this example, we assign boolean values to variables and print them.

</>
Copy
# Assign boolean values
a = True
b = False

# Print the values
print("Value of a:", a)
print("Value of b:", b)

Output:

Value of a: True
Value of b: False

2. Boolean in Conditional Statements

Booleans are commonly used in conditional statements such as if statements.

</>
Copy
# Define a boolean variable
is_raining = True

# Use in a conditional statement
if is_raining:
    print("Take an umbrella!")
else:
    print("Enjoy the sunshine!")

Output:

Take an umbrella!

3. Boolean and Comparison Operators

Comparison operators return Boolean values.

</>
Copy
# Using comparison operators
x = 10
y = 5

print(x > y)  # True, because 10 is greater than 5
print(x == y) # False, because 10 is not equal to 5
print(x < y)  # False, because 10 is not less than 5

Output:

True
False
False

4. Boolean and Logical Operators

Logical operators and, or, and not work with Boolean values.

</>
Copy
# Using logical operators
a = True
b = False

print(a and b)  # False, because both need to be True for AND
print(a or b)   # True, because at least one is True
print(not a)    # False, because not reverses the value

Output:

False
True
False

5. Boolean Values of Different Data Types

Python automatically converts certain values to True or False when used in a boolean context.

</>
Copy
# Checking boolean values of different data types
print(bool(0))        # False (zero is False)
print(bool(1))        # True (non-zero numbers are True)
print(bool(""))       # False (empty string is False)
print(bool("Hello"))  # True (non-empty string is True)
print(bool([]))       # False (empty list is False)
print(bool([1, 2]))   # True (non-empty list is True)

Output:

False
True
False
True
False
True

6. Handling Boolean Errors

One common mistake is using true and false instead of True and False. Python is case-sensitive.

</>
Copy
try:
    val = true  # Incorrect capitalization
except NameError as e:
    print("Error:", e)

Output:

Error: name 'true' is not defined

Always use True and False with proper capitalization to avoid this error.