BOOLEAN EXPRESSION
Boolean expressions in Python are expressions that evaluate to either True
or False
. They are commonly used in conditional statements, loops, and logical operations. Here are some examples of boolean expressions:
Comparison Operators:
Comparison operators are used to compare two values. They return True
if the comparison is true, and False
otherwise.
x = 10
y = 5
# Equal to
print(x == y) # False
# Not equal to
print(x != y) # True
# Greater than
print(x > y) # True
# Less than
print(x < y) # False
# Greater than or equal to
print(x >= y) # True
# Less than or equal to
print(x <= y) # False
Logical Operators:
Logical operators are used to combine multiple boolean expressions.
x = 10
y = 5
# Logical AND
print(x > 5 and y < 10) # True
# Logical OR
print(x < 5 or y > 10) # False
# Logical NOT
print(not(x > 5 and y < 10)) # False
Membership Operators:
Membership operators are used to test if a value is present in a sequence (like a list, tuple, or string).
my_list = [1, 2, 3, 4, 5]
# Membership test
print(3 in my_list) # True
print(6 not in my_list) # True
Identity Operators:
Identity operators are used to compare the memory locations of two objects.
x = [1, 2, 3]
y = [1, 2, 3]
# Identity test
print(x is y) # False
# Negated identity test
print(x is not y) # True
Boolean expressions are fundamental in programming as they allow you to create conditions and make decisions based on those conditions.