How do I check if a value is a boolean in Python?
Richard W
richard w profile pic

In Python, you can check if a value is a boolean using theisinstance() function or by comparing the value to theTrue andFalse literals. Here's a detailed explanation of both approaches: Using the isinstance() function: Theisinstance() function allows you to check the type of a value. To check if a value is a boolean, you can useisinstance(value, bool).

1
2
3
4
5
6
7
8
9
10

def is_boolean(value):
    return isinstance(value, bool)

result1 = is_boolean(True)    # True
result2 = is_boolean(False)   # True
result3 = is_boolean(0)  # False
result4 = is_boolean("True")  # False

print(result1, result2, result3, result4)

In this example, theis_boolean() function checks if thevalue is an instance of thebool type usingisinstance(value, bool). It returnsTrue if the value is a boolean andFalse otherwise. Comparing with True and False literals: Another approach is to directly compare the value to theTrue andFalse literals.

1
2
3
4
5
6
7
8
9
10

def is_boolean(value):
    return value in (True, False)

result1 = is_boolean(True)    # True
result2 = is_boolean(False)   # True
result3 = is_boolean(0)  # False
result4 = is_boolean("True")  # False

print(result1, result2, result3, result4)

In this example, theis_boolean() function checks if thevalue is equal to eitherTrue orFalse usingvalue in (True, False). It returnsTrue if the value is a boolean andFalse otherwise. Summary: To check if a value is a boolean in Python, you can use theisinstance() function to check if the value's type isbool or directly compare the value to theTrue andFalse literals. These approaches allow you to determine if a value represents a boolean and handle boolean-specific operations or logic accordingly in your code.