smartyfy.mrindigi.com

Python Master Course V2 — 014. Logical Operators

SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 014/200

Logical Operators

Estimated study: 60–90 minutes. Prerequisite: Lesson 013

Boolean logic, short circuit evaluation and truthiness.

Video lesson

Video not yet available.

Learning objectives

Explain boolean logic, short circuit evaluation and truthiness, trace control flow, identify boundary cases, debug errors and implement a real-world decision-making project.

Prerequisites: Python 3.10+, variables, types, comparison expressions, and prior course lessons.

Understand and apply: Logical Operators

Three different logical jobs

Use and when every requirement must hold, or when at least one alternative is sufficient, and not to reverse a truth value. For Boolean operands, the four input pairs are easy to check: True/True gives True for both operators; True/False and False/True give False for and but True for or; False/False gives False for both. not True is False and not False is True. State the rule in words before translating it into an expression.

Python conditions also accept non-Boolean objects. Zero, the empty string, empty collections, and None are falsey; ordinary nonempty strings and nonzero numbers are truthy. The string "False" is therefore truthy because it contains characters. Truthiness is useful for checking whether a collection has items, but it does not validate that an external field is really a Boolean. A permission flag should have an explicit Boolean contract.

Trace values, not just True or False

Unlike not, and and or return one of their operands. a and b returns a if it is falsey; otherwise it returns b. a or b returns a if it is truthy; otherwise it returns b. This explains why a default expression can produce a string or number. Use bool(expression) when the interface specifically requires a Boolean, while remembering that conversion does not establish whether an input was valid.

Operand-return behavior

print(0 or 10)
print("ready" and 7)
print("" and "unused")
print(not "False")

Expected output:

10
7

False

The third print produces a blank line: the empty first operand is returned, so the second operand is unnecessary. A common defaulting pattern is name or "Guest". It treats an empty name as missing. That can be correct for names, but quantity or 1 also replaces a legitimate zero. Choose a default only after deciding which values actually mean missing; a later is None check can distinguish absence from zero.

Short-circuiting protects unnecessary work

Python evaluates operands from left to right and stops as soon as the result is determined. If the first operand of and is falsey, the second expression is skipped. If the first operand of or is truthy, the second is skipped. Put a prerequisite before the operation that depends on it, such as checking a divisor before division.

Guard a division

count = 0
safe = count != 0 and 12 / count > 2
print(safe)
count = 3
safe = count != 0 and 12 / count > 2
print(safe)

Expected output:

False
True

With zero, division never runs. With three, the first condition succeeds, division produces 4.0, and the comparison is True. Reversing those operands would remove the protection. Do not hide important updates inside a condition: a skipped function call will not perform its side effect.

Comparisons bind more tightly than not, which binds more tightly than and, then or. Nevertheless, parentheses and named conditions make mixed policies easier to review. For example, require verified and (is_member or has_ticket) when verification is mandatory for either route. Test the all-false case, each route alone, and both routes together. A truth table exposes an accidentally optional requirement more clearly than a single successful example.

Runnable examples

Save each example in a separate lesson_014.py file and run with python lesson_014.py. These are expected outputs, not claims of execution in the browser.

Example 1: and / or / not

age=20
verified=True
print(age>=18 and verified)
print(age<18 or not verified)

Expected output:

True
False

Example 2: Short circuit

def call():
 print("called")
 return True
print(False and call())
print(True or call())

Expected output:

False
True

Guided project: business decision engine

This practical exercise turns a small set of business rules into predictable results. Read each branch, predict the result, then run the test cases. Modify one rule and add tests for its boundaries.

Input contract: This classroom function assumes age and score are validated numbers and verified is a Boolean. It does not validate external data.

def approve(age,verified,score):
 return age>=18 and verified and score>=70
for case in [(20,True,80),(17,True,90),(30,False,95)]:
 print(approve(*case))

Testing: Check ordinary accepted cases, rejected cases, exact thresholds, and malformed inputs. The sample focuses on the lesson’s branching concepts; a production system must additionally validate external inputs and enforce permissions server-side.

Common mistakes and best practices

  • Failing to check invalid values before decision logic.
  • Misunderstanding branch ordering and short-circuit behavior.
  • Using overly complex nested expressions instead of readable predicates.
  • Not testing equality at inclusive thresholds.
  • Confusing illustrative classroom policies with real-world requirements.

Practice and reason it through

Attempt each question before opening its answer. Write down the result and the reason, then compare your reasoning with the worked solution.

1. Which values are returned?

print(0 or 10)
print(0 and 10)
Reveal answer and explanation

The results are 10 and 0. or chooses the first truthy operand, while and stops at its first falsey operand. Neither expression is required to return a Boolean.

Expected output:

10
0

2. Will the helper print anything?

def helper():
    print("helper ran")
    return True

print(False and helper())
print(True or helper())
Reveal answer and explanation

No helper message appears. False determines the first and result; True determines the second or result. Both function calls are skipped, so only the outer print calls produce output.

Expected output:

False
True

3. Repair a guard that still divides by zero.

count = 0
# Proposed condition: 12 / count > 2 and count != 0
Reveal answer and explanation

Check the divisor first. In the original order, Python must evaluate division before it can decide whether to evaluate the right-hand condition. A guard protects only work to its right.

count = 0
print(count != 0 and 12 / count > 2)

Expected output:

False

4. Why does quantity or 1 mishandle an empty order?

quantity = 0
print(quantity or 1)
Reveal answer and explanation

Zero is falsey, so the expression returns 1 and changes the meaning of the order. If zero is a valid quantity, preserve it. If the contract uses None for a missing value, choose the default only when the value is None; do not equate all falsey values with absence.

Expected output:

1

5. Must a ticket holder be verified under this expression?

Reveal answer and explanation

verified and is_member or has_ticket means (verified and is_member) or has_ticket, so any truthy ticket flag allows entry. If verification is required for both routes, group the alternatives. For verified=False, is_member=False, has_ticket=True, the original expression is True and the corrected expression is False.

verified = False
is_member = False
has_ticket = True
print(verified and is_member or has_ticket)
print(verified and (is_member or has_ticket))

Expected output:

True
False

Further challenge

  • Challenge: extend the project with a new policy and document three tests including one boundary case.

Mastery checkpoint

Demonstrate that you can predict the examples, explain branch order, run the project, and write at least three additional tests. Summary: Boolean logic, short circuit evaluation and truthiness require explicit reasoning, validation, and reproducible testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.