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.
- Multi-line strings or block comments start with three consecutive quotes (
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 eitherTrueorFalse.
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, returningTrueorFalse. - Example:
evaluates toFalse. - Example:
evaluates toTrue. - Comparison operators work across multiple data types, including integers, floating-point numbers, and strings.
- Assignment Operator (
Relational Comparison Operators:
- Greater Than (
>): ReturnsTruestrictly if the left value is larger than the right value. Equal values returnFalse(e.g.,evaluates toFalse). - Greater Than or Equal To (
>=): ReturnsTrueif the left value is larger than or equal to the right value (e.g.,evaluates toTrue). - Less Than (
<): ReturnsTruestrictly if the left value is smaller than the right value. - Less Than or Equal To (
<=): ReturnsTrueif the left value is smaller than or equal to the right value. - Not Equal To (
!=): ReturnsTrueif the left and right values are not identical, andFalseif they are identical.
- Greater Than (
Evaluating Variables with Comparison Operators:
- If variable and variable :
- The expression evaluates to , returning
False.
- The expression evaluates to , returning
- If variable and variable :
- The expression evaluates to , returning
False. - The expression evaluates to , returning
True.
- The expression evaluates to , returning
- If variable and variable :
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.
- Calling
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 and :
- The expression evaluates , producing
False.
- The expression evaluates , producing
- Tab characters (
Customizing
print()Separators (sepKeyword 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'instructsprint()to output a tab character between each argument instead of a standard space. sepcan be assigned any arbitrary string value to customize output formatting.
- By default, Python's
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.
- When a print statement contains a logical or mathematical computation, Python evaluates the expression entirely first, then sends the resulting value to
Logical Operators and Truth Tables
Definitions of Logical Operators:
- Logical operators combine or modify Boolean expressions.
andOperator: ReturnsTrueif and only if both the left-hand and right-hand operands evaluate toTrue. If either operand isFalse, the overall result isFalse.orOperator: ReturnsTrueif at least one operand evaluates toTrue. ReturnsFalseonly when both operands areFalse.notOperator: A unary operator that reverses/inverts a Boolean value (not TruebecomesFalse;not FalsebecomesTrue).
Truth Tables:
Logical AND (
x and y):True and TrueTrueTrue and FalseFalseFalse and TrueFalseFalse and FalseFalse
Logical OR (
x or y):True or TrueTrueTrue or FalseTrueFalse or TrueTrueFalse or FalseFalse
Logical NOT (
not x):not TrueFalsenot FalseTrue
Expression Evaluation Examples:
- Given and :
- evaluates to
True and False, returningFalse. - evaluates to
True or False, returningTrue.
- evaluates to
- Evaluating arbitrary mathematical statements:
- evaluates to
False and True, returningFalsebecause is false. - evaluates to
True and True, returningTrue.
- evaluates to
- Given and :
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 cis evaluated as(a and b) and c.- Example: If , (which is
True), and , then(True and True) and Trueevaluates toTrue.
- When chaining identical operators (e.g.,
Practical Applications: Error Checking and Range Validation
Inclusive Range Checking:
- To determine whether a user-input value is inside an inclusive bound between minimum and maximum ( inclusive):
- Logical formula:
value >= x and value <= y
- Logical formula:
- Example with range bounds and :
- Valid inclusive values returning
True: .
- Valid inclusive values returning
- Example trace with age validation:
- Input
age = 18, target range to : - Child check:
18 < 13False. - Range check:
18 >= 13(True)and18 <= 20(True)True.
- Input
- To determine whether a user-input value is inside an inclusive bound between minimum and maximum ( inclusive):
Exclusive / Out-of-Range Checking:
- To determine if a number lies strictly outside a range bounded by
lowandhigh:- Method 1 (Using
or):num < low or num > high- Returns
Trueif the number lies on the number line strictly to the left oflowOR strictly to the right ofhigh.
- Returns
- Method 2 (Using
notwith inclusiveand):not (num >= low and num <= high)- Inverts the result of the inclusive range test.
- Method 1 (Using
- Both methods are logically equivalent.
- To determine if a number lies strictly outside a range bounded by
Dynamic Visual Formatting in Output:
- String multiplication (
*) performs string repetition. len(title)calculates the character count of the stringtitleas 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.
- String multiplication (
Operator Precedence and Complex Logical Expressions
Hierarchy of Operator Precedence:
- Parentheses
(): Highest priority; explicitly overrides default precedence. - Arithmetic Operators: Standard math rules (
**,*,/,//,%,+,-). - Comparison Operators:
==,!=,>,<,>=,<=. - Logical
not: Evaluated before other logical operators. - Logical
and: Evaluated afternotbut beforeor. - Logical
or: Lowest precedence among logical operators.
- Operators with equal precedence evaluate from left to right.
- Parentheses
Detailed Case Study: Course Passing Logic
Course Passing Requirements:
- Course average strictly greater than (
average > 65). - Submitted assignments equal to or greater than (
assignments >= 2). - Attendance choice: Attend at least lectures (
lectures >= 5) OR attend at least labs (labs >= 4).
- Course average strictly greater than (
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)(False or True)True. - Step 2 (Comparisons):
72.5 > 65(True),2 >= 2(True). - Step 3 (
andLeft-to-Right):True and TrueTrue. - Step 4 (
andFinal):True and TrueTrue(Student Passes).
- Student Data:
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 (
andprecedence left-to-right):False and TrueFalse. - Step 3 (
andprecedence next):False and FalseFalse. - Step 4 (
orprecedence last):False or TrueTrue(ERROR: Failing student incorrectly receives a passing grade).
- Student Data:
Conclusion: Parentheses around
orstatements nested withinandlogic are essential to maintain intended evaluation order.
Chained Comparisons in Python:
- Python supports short-hand comparison chaining such as
low <= num <= highas a compact syntactic alternative tonum >= low and num <= high. - Chained comparisons simplify code syntax while preserving exact logical equivalence.
- Python supports short-hand comparison chaining such as