3.16 Boolean Operators and, or and not

Boolean Operator and

  • Ensure that two conditions are both True with the Boolean and operator.
In [1]:
gender = 'Female'
In [2]:
age = 70
In [3]:
if gender == 'Female' and age >= 65:
    print('Senior female')
Senior female
  • Truth table for the and operator:
expression1 expression2 expression1 and expression2
False False False
False True False
True False False
True True True

Boolean Operator or

  • Ensure that one or both of two conditions are True with the Boolean or operator.
In [4]:
semester_average = 83
In [5]:
final_exam = 95
In [6]:
if semester_average >= 90 or final_exam >= 90:
    print('Student gets an A')
Student gets an A
  • Truth table for the or operator:
expression1 expression2 expression1 or expression2
False False False
False True True
True False True
True True True

Improving Performance with Short-Circuit Evaluation

  • Python stops evaluating an and expression as soon as it knows whether the entire condition is False.
  • Python stops evaluating an or expression as soon as it knows whether the entire condition is True.
  • 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.

Boolean Operator not

  • “Reverse” the meaning of a condition.
  • Unary operator—it has only one operand.
In [7]:
grade = 87
In [8]:
if not grade == -1:
    print('The next grade is', grade)
The next grade is 87
In [9]:
if grade != -1:
    print('The next grade is', grade)
The next grade is 87
  • Truth table for the not operator.
expression not expression
False True
True False
  • Precedence and grouping of the operators introduced so far—shown in decreasing order of precedence.
Operators Grouping
() left to right
** right to left
*     /     //    % left to right
+     - left to right
<     <=     >     >=     ==     != left to right
not left to right
and left to right
or left to right

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 3 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.