12:Operations – III (Logical)
Operations – III (Logical)
These operators only work on Boolean values and also produce Boolean results.
- Three Logical Operations are available in Python.
- not (Logical Not)
- or (Logical Or)
- and (Logical and)
- All operands in the logical operations are Boolean, not numbers.
- Logical Not (not) is the simple operator that has only two operands.
- The not operator just invert the logical value of variable. If the value is True then it will convert to False and if it is False then convert to True.
x = Truey = not xprint (y)
Code 1: Using Logical Not (not)
- We create a Boolean variable x and save True in it.
- On line 2, we apply the not operator on variable x.
- This operation inverts the value in x and stores it into y.
- Hence the printed value of y will be False.
- Logical Or (or) operators have three operands.
- It performs operations between two logical values (Boolean values) and stores the result in logical form.
x = Truey = Falsez = x or y
Code 2: Using OR Operator
- The value of z after or operation between x and y will be True
- The result of the operation can be found by this truth table.
- Logical (and) also perform between two values or variables.
- The truth table for (and) operation is as follows.
- The and and or also used to combine the results of comparison operators.
x = Truey = Falsez = Falsed = x or y or z
Code 3: Using multiple or operations
- We can see that first an or operation between x and y. This operation will produce True (according to truth table)
- Consequently, this True will or with z and again produce True which will store in d.
x = Truey = Falsez = Falsea = 10b = 20p = a == bq = a < br = b >= 20d = (not x) or p and q or r and (not y) or (a < 10)
Code 4: A Complex Expression using Logical Operations
- We set the value of x to True, y to False, z to False, a to 10 (integer), b to 20.
- Then p will be the value False because both are not the same.
- q will be True because a is less than b.
- r will True because b is equal to 20 (surely not greater than).
- The final expression is fairly complex.
- First, the (not x) will perform because it is written in parenthesis and invert the value of x that produces False.
- Then (not y) will perform and produce True.
- Then (a < 10) will produce False.
- After execution of parenthesis operation our expression seems like this
- d False or p and q or r and True or False
- Now it will start solving and operations.
- First, p and q will resolve and produce True
- Then r and True will produce True
- Now expression like this
- d False or True or True or False
- Now all the expressions will produce True and it will store to d.
- Like comparison operators, logical operators are also used in decision making.








