Using Boolean Operators
In Python, you can use boolean operators to combine and manipulate boolean values. The three main boolean operators are and, or, and not.
The and Operator
The and operator returns True if both operands are True, and False otherwise. It can be used to check if multiple conditions are met simultaneously.
age = 25
is_student = True
is_employed = False
is_eligible = (age >= 18) and (is_student or is_employed)
print(is_eligible) ## Output: True
In the example above, the is_eligible variable is True because the person is 18 or older and either a student or employed.
The or Operator
The or operator returns True if at least one of the operands is True, and False if both operands are False. It can be used to check if at least one of the conditions is met.
is_student = True
is_employed = False
can_access_discount = is_student or is_employed
print(can_access_discount) ## Output: True
In this case, the can_access_discount variable is True because the person is either a student or employed.
The not Operator
The not operator is a unary operator that negates the boolean value of its operand. It returns True if the operand is False, and False if the operand is True.
is_adult = True
is_not_adult = not is_adult
print(is_not_adult) ## Output: False
Here, the is_not_adult variable is False because the is_adult variable is True.
By understanding how to use these boolean operators, you can create more complex and powerful logical conditions in your Python code, enabling you to make more sophisticated decisions and control the flow of your programs.