Uncategorized

12:Operations – III (Logical)

Operations – III (Logical)

These operators only work on Boolean values and also produce Boolean results.

  1. Three Logical Operations are available in Python.
  2. not (Logical Not)
  3. or (Logical Or)
  4. and (Logical and)
  5. All operands in the logical operations are Boolean, not numbers.
  6. Logical Not (not) is the simple operator that has only two operands.
  7. 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)

  1. We create a Boolean variable x and save True in it.
  2. On line 2, we apply the not operator on variable x.
  3. This operation inverts the value in x and stores it into y.
  4. Hence the printed value of y will be False.
  5. Logical Or (or) operators have three operands.
  6. 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

  1. The value of z after or operation between x and y will be True
  2. The result of the operation can be found by this truth table.

  1. Logical (and) also perform between two values or variables.
  2. The truth table for (and) operation is as follows.

  1. 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

  1. We can see that first an or operation between x and y. This operation will produce True (according to truth table)
  2. 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

  1. We set the value of x to True, y to False, z to False, a to 10 (integer), b to 20.
  2. Then p will be the value False because both are not the same.
  3. q will be True because a is less than b.
  4. r will True because b is equal to 20 (surely not greater than).
  5. 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
  1. Now it will start solving and operations.
  2. First, p and q will resolve and produce True
  3. Then r and True will produce True
  4. Now expression like this
  • d False or True or True or False
  1. Now all the expressions will produce True and it will store to d.
  2. Like comparison operators, logical operators are also used in decision making.

Leave a Reply

Your email address will not be published. Required fields are marked *