Logical Operations

AND Operator

  1. # and - both must be True
  2. True and True
  3. #ans: True
  4. True and False
  5. #ans: False
  6. False and True
  7. #ans: False
  8. False and False
  9. #ans: False

OR Operator

  1. # or - at least one True
  2. True or False
  3. #ans: True
  4. False or True
  5. #ans: True
  6. False or False
  7. #ans: False
  8. True or True
  9. #ans: True

NOT Operator

  1. # not - inverts boolean
  2. not True
  3. #ans: False
  4. not False
  5. #ans: True
  6. not (5 > 3)
  7. #ans: False

Combining Conditions

  1. # combining with and
  2. x = 10
  3. x > 5 and x < 15
  4. #ans: True
  5. #ans: combining with or
  6. x < 5 or x > 8
  7. #ans: True

Short Circuit Evaluation

  1. # and stops at first False
  2. False and (1/0)
  3. #ans: False (no error, doesn't evaluate 1/0)
  4. #ans: or stops at first True
  5. True or (1/0)
  6. #ans: True (no error)

Exercises - Part 1

  1. # what is the result?
  2. True and True
  3. #ans: True
  4. # short circuit evaluation?
  5. False and (1/0)
  6. #ans: False (no error, doesn't evaluate second part)

Exercises - Part 2

  1. # short circuit with or?
  2. True or (1/0)
  3. #ans: True (no error)
  4. # what about this?
  5. not False
  6. #ans: True

Exercises - Part 3

  1. # chaining and/or?
  2. True or False and False
  3. #ans: True (and has higher precedence)
  4. # boolean with comparison?
  5. 5 > 3 and 10 < 20
  6. #ans: True

Exercises - Part 4

  1. # tricky: what is this?
  2. bool([]) and bool([1])
  3. #ans: False
  4. # what evaluates?
  5. 0 or 5
  6. #ans: 5 (returns last truthy value)

Exercises - Part 5

  1. # and returns?
  2. 5 and 10
  3. #ans: 10 (returns last value if all truthy)
  4. # mixed types?
  5. "hello" and ""
  6. #ans: "" (returns last value or first falsy)

Exercises - Part 6

  1. # what about this?
  2. not not True
  3. #ans: True
  4. # De Morgan's law?
  5. not (True and False)
  6. #ans: True
  7. not True or not False
  8. #ans: True

Exercises - Part 7

  1. # order of precedence?
  2. True and False or True
  3. #ans: True (and first, then or)
  4. # empty values?
  5. [] or [1, 2]
  6. #ans: [1, 2]

Google tag (gtag.js)