BOOLEAN OPERATORS AND, OR AND NOT
The conditional operators >, <, >=, <=, == and != can be used to form simple conditions such as grade >= 60. To form more complex conditions that combine simple conditions, use the and, or and not Boolean operators.
Boolean Operator and
To ensure that two conditions are both True before executing a control statement’s suite, use the Boolean and operator to combine the conditions. The following code defines two variables, then tests a condition that’s True if and only if both simple conditions are True—if either (or both) of the simple conditions is False, the entire and expression is False:
In [2]: age = 70
In [3]: if gender == 'Female' and age >= 65:
...: print('Senior female')
...:
Senior female
The if statement has two simple conditions:
- gender == 'Female' determines whether a person is a female and
- age >= 65 determines whether that person is a senior citizen.
(gender == 'Female') and (age >= 65)
Boolean Operator or
Use the Boolean or operator to test whether one or both of two conditions are True. The following code tests a condition that’s True if either or both simple conditions are True—the entire condition is False only if both simple conditions are False:
In [5]: final_exam = 95
In [6]: if semester_average >= 90 or final_exam >= 90:
...: print('Student gets an A')
...:
Student gets an A
Snippet [6] also contains two simple conditions:
- semester_average >= 90 determines whether a student’s average was an A (90 or above) during the semester, and
- final_exam >= 90 determines whether a student’s finalexam grade was an A.
Improving Performance with Short-Circuit Evaluation
So the condition
gender == 'Female' and age >= 65
Similarly, the condition
semester_average >= 90 or final_exam >= 90
In expressions that use and, make the condition that’s more likely to be False the leftmost condition. In or operator expressions, make the condition that’s more likely to be True the leftmost condition. These techniques can reduce a program’s execution time.
Boolean Operator not
The Boolean operator not “reverses” the meaning of a condition—True becomes False and False becomes True. This is a unary operator—it has only one operand. You place the not operator before a condition to choose a path of execution if the original condition (without the not operator) is False, such as in the following code:
In [8]: if not grade == -1:
...: print('The next grade is', grade)
...:
The next grade is 87
Often, you can avoid using not by expressing the condition in a more “natural” or convenient manner. For example, the preceding if statement can also be written as follows:
...: print('The next grade is', grade)
...:
The next grade is 87