Dcit 22 Lesson 05 Logical Operators
Dcit 22 Lesson 05 Logical Operators
LOGICAL OPERATORS
OBJECTIVES
After the completion of this chapter, the students should be able to:
1. Understand how to use logical operators in programming; and
2. Construct a program that will use the different kinds of logical operations.
LOGICAL OPERATORS
Operators are used to perform operations on values and variables. These are the special
symbols that carry out arithmetic and logical computations. The value the operator operates
on is known as Operand.
In Python, Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR and Logical NOT operations.
• Logical operator returns True if both the operands are True else it returns False
• The AND operator checks whether two conditions are both True simultaneously:
The following table illustrates the result of the and operator when combining two conditions:
a b a and b
True True True
True False False
False False False
False True False
1|Page
Example 2
Example 3
Logical OR operator
2|Page
a b a or b
True True True
True False True
False True True
False False False
Example 1
Example 2
Example 3
• Logical not operator work with the single Boolean value. If the Boolean value is True it
returns False and vice-versa.
• The not operator applies to one condition. And it reverses the result of that condition,
True becomes False and False becomes True.
3|Page
a not a
True False
False True
Example 1
Example 2
Example 3
4|Page
When you mix the logical operators in an expression, Python will evaluate them in the order
which is called the operator precedence.
The following shows the precedence of the not, and, and or operators:
Operator Precedence
not High
and Medium
or Low
Based on these precedences, Python will group the operands for the operator with the highest
precedence first, then group the operands for the operator with the lower precedence, and so
on.
In case an expression has several logical operators with the same precedence, Python will
evaluate them from the left to right:
Example Problems
1. Create a program where the user can input a grade of a students. If the grade is greater
than 70, display the grade and the message “PASSED”. However, if the grade is less
than 70, display the grade and the message “FAILED”.
5|Page
3. Create a simple calculator. The user can choose what operator to be use. “Addition”
for adding of two numbers, “Subtraction” for subtracting of two numbers,
“Multiplication” for multiplying two numbers, “Division” for dividing two numbers, and
“Exit” for terminating the program. If the user entered invalid input display “Invalid
Input!” The program must accept either all lowercase, all uppercase, or sentence case.
6|Page