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.
True
— represents a true conditionFalse
— represents a false conditionPython treats several values as falsy, meaning they evaluate to False
when converted to boolean:
None
False
0, 0.0, 0j
'', [], (), {}
All other values are considered truthy (evaluate to True
).
a = True
b = False
if a:
print("a is True")
if not b:
print("b is False")
Python supports logical operators to combine boolean expressions:
and
— True if both operands are Trueor
— True if at least one operand is Truenot
— negates the boolean valuex = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
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
True
or False
explicitly. Instead, use the variable directly:# Prefer this:
if is_active:
print("Active")
# Over this:
if is_active == True:
print("Active")
is_valid
, has_errors
.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.")