Python Comparison Operators Logical Operators and Range Validation Notes

Documentation Strings and Multi-Line Comments in Python

  • Multi-Line Comment Syntax (Docstrings):
    • Multi-line strings or block comments start with three consecutive quotes (""" or ''') and end with three consecutive quotes (""" or ''').
    • They allow text to span across any number of lines without requiring the hash symbol (#) at the beginning of each line.
    • Python's interpreter ignores unassigned docstring blocks during execution, allowing them to serve as source code documentation.

Python Comparison Operators

  • Definition and Boolean Return Values:

    • Comparison operators compare two values and evaluate the relationship between them.
    • Every comparison operation always returns a Boolean value (bool), which is strictly either True or False.
  • Equality Operator (==) vs. Assignment Operator (=):

    • Assignment Operator (=): Evaluates the expression on the right-hand side and assigns the resulting value into the variable on the left-hand side.
    • Equality Operator (==): Asks whether the value on the left-hand side equals the value on the right-hand side, returning True or False.
    • Example: 5==75 == 7 evaluates to False.
    • Example: 42==4242 == 42 evaluates to True.
    • Comparison operators work across multiple data types, including integers, floating-point numbers, and strings.
  • Relational Comparison Operators:

    • Greater Than (>): Returns True strictly if the left value is larger than the right value. Equal values return False (e.g., 5>55 > 5 evaluates to False).
    • Greater Than or Equal To (>=): Returns True if the left value is larger than or equal to the right value (e.g., 5>=55 >= 5 evaluates to True).
    • Less Than (<): Returns True strictly if the left value is smaller than the right value.
    • Less Than or Equal To (<=): Returns True if the left value is smaller than or equal to the right value.
    • Not Equal To (!=): Returns True if the left and right values are not identical, and False if they are identical.
  • Evaluating Variables with Comparison Operators:

    • If variable x=5x = 5 and variable y=10y = 10:
      • The expression x==yx == y evaluates to 5==105 == 10, returning False.
    • If variable x=5x = 5 and variable y=5y = 5:
      • The expression x>yx > y evaluates to 5>55 > 5, returning False.
      • The expression x>=yx >= y evaluates to 5>=55 >= 5, returning True.

Formatting Output and User Input Handling

  • Unprompted Input Execution:

    • Calling input() without a string argument does not display any prompt text to the user, but still halts program execution to wait for user input followed by the Enter key.
    • When collecting multiple inputs sequentially (e.g., calling input() twice for two numbers), the program waits for the user to submit the first input, then immediately waits for the second input.
  • Text Output Alignment with Escape Sequences:

    • Tab characters (\t) inserted into print strings shift output columns to achieve clean, right-justified alignment across multiple printed lines.
    • Example evaluation with inputs num1=10\text{num}_1 = 10 and num2=15\text{num}_2 = 15:
      • The expression num1>num2\text{num}_1 > \text{num}_2 evaluates 10>1510 > 15, producing False.
  • Customizing print() Separators (sep Keyword Argument):

    • By default, Python's print() function inserts a single space between each comma-separated argument.
    • The default separator behavior can be overridden using the keyword argument sep (e.g., print(val1, val2, sep='\t')).
    • Setting sep='\t' instructs print() to output a tab character between each argument instead of a standard space.
    • sep can be assigned any arbitrary string value to customize output formatting.
  • Expression Evaluation Order inside print():

    • When a print statement contains a logical or mathematical computation, Python evaluates the expression entirely first, then sends the resulting value to print() for console display.

Logical Operators and Truth Tables

  • Definitions of Logical Operators:

    • Logical operators combine or modify Boolean expressions.
    • and Operator: Returns True if and only if both the left-hand and right-hand operands evaluate to True. If either operand is False, the overall result is False.
    • or Operator: Returns True if at least one operand evaluates to True. Returns False only when both operands are False.
    • not Operator: A unary operator that reverses/inverts a Boolean value (not True becomes False; not False becomes True).
  • Truth Tables:

    • Logical AND (x and y):

      • True and True →\rightarrow True
      • True and False →\rightarrow False
      • False and True →\rightarrow False
      • False and False →\rightarrow False
    • Logical OR (x or y):

      • True or True →\rightarrow True
      • True or False →\rightarrow True
      • False or True →\rightarrow True
      • False or False →\rightarrow False
    • Logical NOT (not x):

      • not True →\rightarrow False
      • not False →\rightarrow True
  • Expression Evaluation Examples:

    • Given a=Truea = \text{True} and b=Falseb = \text{False}:
      • a and ba \text{ and } b evaluates to True and False, returning False.
      • a or ba \text{ or } b evaluates to True or False, returning True.
    • Evaluating arbitrary mathematical statements:
      • (5>10) and (7<10)(5 > 10) \text{ and } (7 < 10) evaluates to False and True, returning False because 5>105 > 10 is false.
      • (5<10) and (7<10)(5 < 10) \text{ and } (7 < 10) evaluates to True and True, returning True.
  • Chaining Logical Operators and Precedence Direction:

    • When chaining identical operators (e.g., a and b and c), Python evaluates expressions from left to right.
    • a and b and c is evaluated as (a and b) and c.
    • Example: If a=Truea = \text{True}, b=(5==5)b = (5 == 5) (which is True), and c=Truec = \text{True}, then (True and True) and True evaluates to True.

Practical Applications: Error Checking and Range Validation

  • Inclusive Range Checking:

    • To determine whether a user-input value is inside an inclusive bound between minimum xx and maximum yy (x×value×yx \times \text{value} \times y inclusive):
      • Logical formula: value >= x and value <= y
    • Example with range bounds x=2x = 2 and y=7y = 7:
      • Valid inclusive values returning True: 2,3,4,5,6,72, 3, 4, 5, 6, 7.
    • Example trace with age validation:
      • Input age = 18, target range 1313 to 2020:
      • Child check: 18 < 13 →\rightarrow False.
      • Range check: 18 >= 13 (True) and 18 <= 20 (True) →\rightarrow True.
  • Exclusive / Out-of-Range Checking:

    • To determine if a number lies strictly outside a range bounded by low and high:
      • Method 1 (Using or): num < low or num > high
        • Returns True if the number lies on the number line strictly to the left of low OR strictly to the right of high.
      • Method 2 (Using not with inclusive and): not (num >= low and num <= high)
        • Inverts the result of the inclusive range test.
    • Both methods are logically equivalent.
  • Dynamic Visual Formatting in Output:

    • String multiplication (*) performs string repetition.
    • len(title) calculates the character count of the string title as an integer.
    • Formula for line dividers: lines = '-' * len(title) + ' '
    • Produces a line of hyphens matching the length of title, creating an underline header effect in output.

Operator Precedence and Complex Logical Expressions

  • Hierarchy of Operator Precedence:

    1. Parentheses (): Highest priority; explicitly overrides default precedence.
    2. Arithmetic Operators: Standard math rules (**, *, /, //, %, +, -).
    3. Comparison Operators: ==, !=, >, <, >=, <=.
    4. Logical not: Evaluated before other logical operators.
    5. Logical and: Evaluated after not but before or.
    6. Logical or: Lowest precedence among logical operators.
    • Operators with equal precedence evaluate from left to right.
  • Detailed Case Study: Course Passing Logic

    • Course Passing Requirements:

      1. Course average strictly greater than 6565 (average > 65).
      2. Submitted assignments equal to or greater than 22 (assignments >= 2).
      3. Attendance choice: Attend at least 55 lectures (lectures >= 5) OR attend at least 44 labs (labs >= 4).
    • Correct Expression (With Explicit Parentheses):

      • average > 65 and assignments >= 2 and (lectures >= 5 or labs >= 4)
    • Execution Trace 1 (Passing Student):

      • Student Data: average = 72.5, assignments = 2, lectures = 1, labs = 4.
      • Step 1 (Parentheses execution): (1 >= 5 or 4 >= 4) →\rightarrow (False or True) →\rightarrow True.
      • Step 2 (Comparisons): 72.5 > 65 (True), 2 >= 2 (True).
      • Step 3 (and Left-to-Right): True and True →\rightarrow True.
      • Step 4 (and Final): True and True →\rightarrow True (Student Passes).
    • Execution Trace 2 (Failing Student - Parentheses Bug Analysis):

      • Student Data: average = 25.34 (Failing grade), assignments = 2, lectures = 1, labs = 4.
      • Incorrect Expression (Missing Parentheses): average > 65 and assignments >= 2 and lectures >= 5 or labs >= 4
      • Step 1 (Comparisons): 25.34 > 65 (False), 2 >= 2 (True), 1 >= 5 (False), 4 >= 4 (True).
      • Expression becomes: False and True and False or True.
      • Step 2 (and precedence left-to-right): False and True →\rightarrow False.
      • Step 3 (and precedence next): False and False →\rightarrow False.
      • Step 4 (or precedence last): False or True →\rightarrow True (ERROR: Failing student incorrectly receives a passing grade).
    • Conclusion: Parentheses around or statements nested within and logic are essential to maintain intended evaluation order.

  • Chained Comparisons in Python:

    • Python supports short-hand comparison chaining such as low <= num <= high as a compact syntactic alternative to num >= low and num <= high.
    • Chained comparisons simplify code syntax while preserving exact logical equivalence.