Boolean Laws, Guards and Input Domains
Original Academy explanation and executable experiments accompanying the complete assigned Conditionals chapter. Distinguish a mathematical identity, the Python expression that tests it and the input domain on which a transformation is valid.
Read Boolean laws as parenthesized propositions
The complete assigned Conditionals chapter develops truth tables, branching, early returns, logical opposites, conversion and a charting exercise. Its section 5.4 presents algebraic laws in code-like notation. When testing such a law in Python, explicitly parenthesize each side of the claimed equality. Otherwise comparison precedence can change the question being executed. This orientation retains the original source while making the executable interpretation precise.
For example, the intended proposition is (x and False) == False for a Boolean x. Set x=False. The parenthesized left side produces False, and comparing it with False produces True. Without those parentheses, x and False == False is parsed as x and (False == False). The comparison produces True, then False and True produces False. The failed expression did not refute Boolean algebra: it tested a different expression. Print the intermediate results before changing the law or the expected answer.
The same discipline applies to commutativity and De Morgan's laws. For Boolean values p and q, test (p and q) == (q and p), and test (not (p and q)) == ((not p) or (not q)). There are four input pairs, so an exhaustive truth table covers this deliberately finite domain. It does not prove that arbitrary Python objects, repeated function calls or external actions may be rearranged freely. State the operand domain as part of the argument.
A truth value and an operator's returned value differ
Python's and and or short-circuit and return an operand. They do not always manufacture a bool. For example, 2 and 3 returns 3, while 3 and 2 returns 2. Both results are truthy, but they are different values. Similarly 0 or 17 returns 17, while 2 or 17 returns 2. This makes the idiom measured or fallback unsuitable when zero is a legitimate measurement. To replace only an absent None, use an explicit absence test.
Evaluation order is observable even with Boolean results. Suppose a synthetic probe raises an exception. False and probe() skips the call and returns False. probe() and False calls the probe first and raises. A rewrite that preserves a truth table over already computed Boolean values need not preserve a program's errors or effects. The supplied laboratory records which probes actually run; it does not send messages or invoke an external service.
Worked guard: establish a denominator before division
A report has total=42 cents, count=0 and a minimum mean of 10 cents. The condition count != 0 and total/count >= 10 returns False without dividing. Reversing the two operands raises ZeroDivisionError before the guard can help. A guard must precede the operation whose precondition it establishes. After type validation, a positive count also allows an exact integer comparison: total >= threshold*count. The laboratory uses this form to avoid rounding a quotient. For count 4, 42 >= 40 is True; for count 5, 42 >= 50 is False; for count zero the condition is False and no mean is invented.
State the ordered domain before replacing a logical opposite
The chapter's comparison-opposite examples presume values for which the relevant order comparison behaves as an ordinary ordered comparison. Floating-point NaN is an important boundary. With n=float('nan'), n>=100 is False, so not(n>=100) is True. But n<100 is also False. Therefore replacing the negation with the apparent opposite changes the result on this input. A rule that is valid over ordered finite numbers was extended outside its domain.
Reject NaN and infinities before interpreting a numerical threshold. Type conversion alone is insufficient because float('nan') successfully creates a float. The original delay classifier accepts only built-in int and float values, excluding bool; floats must be finite and all values nonnegative. Arbitrarily large Python integers remain finite integers and need not be converted to float merely to classify them. These are explicit synthetic-data rules, not an inference that every application must use the same policy.
Design a branch partition and test its boundaries
For a fictional report, delays below 100 milliseconds are fast; delays from 100 inclusive to 200 exclusive are standard; all larger finite nonnegative delays are slow. In an if/elif chain, the first branch captures [0,100). At the second branch, the first test is already false, so a test of value<200 captures [100,200). The final branch captures [200,infinity) within the validated domain. These bands are disjoint and exhaustive for accepted inputs.
At 99.9 the result is fast; 100 and 199.9 are standard; 200 is slow. Test values immediately below, exactly at and immediately above each cut. Testing only 50 and 250 misses both inclusion decisions. Validation occurs before all three branches: an invalid NaN must not fall through into slow merely because both less-than comparisons return False. A suite that visits every branch can still miss this input-contract defect.
Independent transfer and explained counterexamples
First evaluate the parenthesized law and the unparenthesized expression for x=True and x=False, recording the intermediate comparison. Next predict which of two probes runs for True or probe(), and explain whether swapping operands is justified. Then classify [99.9,100,199.9,200] under the stated bands and specify the response to NaN, -1, True and the text '100'. Finally decide whether a total of -5 over one present record meets a threshold of -6, and explain why count zero is a different case. Attempt the record before opening its reasoning. Practice remains optional.
Compare the complete independent reasoning
For x=True, both expressions evaluate to True; for x=False, the parenthesized law is True while the unparenthesized expression is False. In the latter, False==False is evaluated before and. True or probe() does not evaluate the probe. Moving the probe to the left can run it and change the program’s errors or effects. The four valid delays classify as fast, standard, standard and slow. NaN and -1 violate the numerical contract and raise ValueError; True and the string 100 violate the type contract and raise TypeError. A negative total of -5 over one present record has mean -5, which meets the threshold -6. With count zero, a mean is undefined; enough_per_record returns False rather than dividing or fabricating an average.
Run the laboratory
Copy to boolean_lab.py and run python boolean_lab.py with Python 3. Seven test groups inspect actual expression values, evaluated probes, exceptions, guard order, exact integer thresholds, finite-input validation and band boundaries.
Source SHA-256: 9d2b356db259f19c0aeee21c1e5696139e4844f967f1d52e307d0b3c1ed2d8ca
Complete Python source and executable tests
Read the sources
- Complete assigned Conditionals chapter, including exercises and figures
- Python reference — Boolean operations
- Python reference — precedence
- Python reference — finite numerical values
The original source is retained with its attribution and notices. This orientation concerns executable interpretation and domain assumptions. The remaining full unit-2 readings and full-course academic acceptance remain open; the examples here are synthetic and all practice is optional.