Foundations of Control Structures, Boolean Logic, and Relational Operations in Python

Sequential Programming Versus Control Structures

  • Sequential Programming Characteristics:

    • Sequential code executes deterministically from top to bottom.

    • Every single line of code written in a sequential program is consecutively interpreted and executed by the runtime environment.

    • While sequential programming is foundational and effective for linear computations, it cannot address problems requiring alternative paths, repetitions, or condition-based branching.

  • Definition and Purpose of Control Structures:

    • A control structure is a programming mechanism that alters the default linear flow of execution.

    • Control structures allow programs to:

    • Skip specific sections of code based on conditions.

    • Repeat code blocks iteratively until criteria are satisfied.

    • Make automated decisions dynamically during execution.

    • Mastery of control structures, alongside basic sequential operations, enables a programmer to implement algorithms capable of solving any computationally solvable problem.

Flowchart Representations of Program Flow

  • Standard Sequential Flowchart Elements:

    • Rectangles: Represent computational processing steps, data input requests, and output operations (e.g., prompting user input, processing calculations, and printing display values).

  • Decision-Making Elements (Selection Structures):

    • Diamond Symbol: Represents a decision-making structure in a flowchart.

    • The diamond evaluates a condition that resolves strictly to a binary outcome: Yes or No (or True or False).

    • Branching behavior example:

    • Query inside diamond: "Is it raining?"

    • If outcome is True (TT): The flow directs to an action such as "Take an umbrella".

    • If outcome is False (FF): The flow proceeds directly to "Good to go" or "Go outside".

  • Iterative Elements (Repetition Structures):

    • Flowchart diamonds are also utilized to establish loops (repetition structures) by routing execution back to previous states based on the evaluation.

    • Calendar repetition example:

    • Decision condition: "Are we still in the semester of Fall 2026?"

    • If True: Execute action "Go to class", increment the date, and loop back to re-evaluate the condition.

    • Termination: Once the calendar reaches December and the semester concludes, the condition evaluates to False, terminating the loop.

  • Multi-Branch Flowchart Example:

    • Step 1: Program starts.

    • Step 2: Diamond evaluates "Is it raining?"

    • If No: Proceed to "Go outside".

    • If Yes: Evaluate second diamond "Do you have an umbrella?"

      • If No: Execute "Wait a while" and loop back to the initial inquiry "Is it raining?"

      • If Yes: Proceed forward.

The Boolean Data Type (bool)

  • Core Definition:

    • Represented in Python by the built-in type identifier bool.

    • Can store exactly one of two discrete states: True or False.

    • Syntax requirement: In Python, True and False must always be written with an initial capital letter (T and F). Lowercase variations without capitalization cause syntax or name errors.

  • Python Shell Type Inspections:

    • type(True) evaluates to <class 'bool'>

    • type(False) evaluates to <class 'bool'>

    • type(0) evaluates to <class 'int'>

    • type(3.14) evaluates to <class 'float'>

    • type('FAU') evaluates to <class 'str'>

  • Comparison of Variable Data Types:

    • isFrute = "True" evaluates to <class 'str'> due to enclosing quotation marks.

    • is_vegetable = 0 evaluates to <class 'int'>.

    • is_dessert = False evaluates to <class 'bool'>.

    • Reassignment side effect: Reassigning is_dessert = 0 dynamically modifies the type of is_dessert from <class 'bool'> to <class 'int'>.

  • Language-Level Differences (Python vs. C/C++):

    • Python contains an inherent, built-in primitive bool data type.

    • Traditional C does not feature an intrinsic, native Boolean type in the same manner without importing specific libraries, relying instead on integer primitives (00 for false, non-zero for true).

Boolean Type Conversions

  • The bool() Type Conversion Function:

    • The bool() constructor attempts to convert any supplied argument into its Boolean equivalent.

    • Universal Rule: The bool() function evaluates to True for almost all values, with strictly defined exceptions.

    • Falsy Values: The function returns False exclusively when supplied with:

    • Numerical zero values: 0, 0.0, 0.000

    • Empty collection or string structures: "" (an empty string containing zero characters)

    • Specific null/empty primitives.

  • Evaluation of Conversion Exercises:

    • bool(0.000) yields False because the underlying value evaluates numerically to zero.

    • bool(-1) yields True because any non-zero integer evaluates to true.

    • bool("") yields False due to being an empty string.

    • bool("...") (a string containing punctuation or symbols) yields True because the string is non-empty.

    • bool(str_returning_function()) yields True as long as the output is a non-empty string sequence.

    • Sensitivity: Altering 0.000 to a non-zero float such as 0.1 immediately causes bool(0.1) to return True.

  • Converting Booleans to Other Data Types:

    • Converting Boolean states to numeric types evaluates according to binary definitions (False=0\text{False} = 0, True=1\text{True} = 1):

    • int(True) yields 1

    • int(False) yields 0

    • float(True) yields 1.0

    • float(False) yields 0.0

    • Converting Boolean states to string representations preserves the literal capitalized name within quotes:

    • str(True) yields 'True'

    • str(False) yields 'False'

Relational and Comparison Operators

  • Definition of Boolean Expressions:

    • An expression is any syntactic combination of variables, constants, operators, and function calls.

    • A Boolean expression is an expression that specifically evaluates to a Boolean truth value (True or False).

  • The Six Relational Operators:

    • == (Equal to): Evaluates if two operands have identical values (e.g., 2 == 2 is True; 2 == 3 is False; 'A' == 'a' is False). Requires two consecutive equal signs without intervening spaces.

    • != (Not equal to): Evaluates if two operands possess different values (e.g., 'A' != 'a' is True).

    • < (Less than): Evaluates if the left operand is strictly smaller than the right (e.g., 2 < 3 is True).

    • > (Greater than): Evaluates if the left operand is strictly larger than the right (e.g., 2 > 3 is False).

    • <= (Less than or equal to): Evaluates if the left operand is smaller than or equal to the right (e.g., 2 <= 3 is True).

    • >= (Greater than or equal to): Evaluates if the left operand is larger than or equal to the right (e.g., 2 >= 3 is False).

  • Evaluation Mechanics and Type Rules:

    • Given X=14X = 14: The expression compareResult = (X <= 13) evaluates 14 <= 13, yielding False, which is stored in compareResult.

    • Mixed Numeric Comparisons: Evaluating 4 < 4.0 returns False. The interpreter compares numeric values directly across numerical types (int and float); since 44 is mathematically equal to 4.04.0, it is not strictly less.

    • Incompatible Type Comparisons: Evaluating comparison expressions between incompatible types (such as an integer and an alphabetical string, e.g., 4 < "AB") results in a runtime error (TypeError).

Lexicographical String Comparison and ASCII Encoding

  • ASCII Comparison Principles:

    • When relational operators compare two strings, they do not assess string length or the physical size of represented objects.

    • Strings are evaluated character-by-character from left to right using the underlying numeric ASCII (American Standard Code for Information Interchange) code points.

  • Character Value Distribution in ASCII:

    • Uppercase English letters (’A’\text{'A'} through ’Z’\text{'Z'}) precede lowercase letters.

    • Uppercase ’A’\text{'A'} corresponds to ASCII value 6565.

    • Uppercase ’Z’\text{'Z'} corresponds to ASCII value 65+25=9065 + 25 = 90.

    • Lowercase letters (’a’\text{'a'} through ’z’\text{'z'}) possess larger numerical values, starting at 9797 and extending past 100100.

    • Consequently, any lowercase character is strictly greater than any uppercase character in an ASCII comparison (e.g., 'a' > 'A' is True).

  • String Comparison Case Studies:

    • "dog" vs. "cat":

    • The evaluation compares the first index character: 'd' vs. 'c'.

    • In the ASCII table, 'd' occurs after 'c', meaning the ASCII value of 'd' is greater than 'c'.

    • Thus, "dog" < "cat" evaluates to False (109 students selected false in lecture poll).

    • "Cat" vs. "cat":

    • Comparing index 00: uppercase 'C' vs. lowercase 'c'.

    • Because lowercase characters possess higher ASCII indices than uppercase characters, 'c' > 'C'.

    • Thus, "cat" > "Cat" is True.

    • "cat" vs. "cats":

    • Characters at index 00, 11, and 22 are identical ('c', 'a', 't').

    • The string "cat" terminates with a null character (ASCII 0\text{ASCII } 0), whereas "cats" contains 's' at index 33.

    • Thus, "cats" > "cat" evaluates to True.

    • "cilantro" vs. "coriander":

    • Index 00 matches ('c' == 'c').

    • Index 11 compares 'i' with 'o'. Because 'o' succeeds 'i' alphabetically and numerically in ASCII, 'o' > 'i'.

    • Thus, "coriander" > "cilantro" evaluates to True.

Boolean Logical Operators

  • Overview of Logical Operators:

    • Alongside the 6 relational operators, programming relies on 3 logical Boolean operators: and, or, and not (providing 9 total decision operators).

  • The and Operator:

    • A binary operator requiring two Boolean operands (left and right).

    • Both operands must evaluate to True for the compound expression to yield True.

    • Truth Table for and:

    • True and True →\rightarrow True

    • True and False →\rightarrow False

    • False and True →\rightarrow False

    • False and False →\rightarrow False

    • Real-world analogy: A joint bank account requiring an "AND" mandate requires both account holders to be present simultaneously to authorize a withdrawal.

  • The or Operator:

    • A flexible binary operator requiring only one operand to evaluate to True to yield a result of True.

    • Evaluates to False exclusively when both operands are False.

    • Truth Table for or:

    • True or True →\rightarrow True

    • True or False →\rightarrow True

    • False or True →\rightarrow True

    • False or False →\rightarrow False

    • Real-world analogy: A joint bank account with an "OR" mandate allows either individual party to withdraw funds independently.

  • Practical Applications of Compound Conditions:

    • Multi-variable threshold checking:

    • temperature < 85 and humidity > 0.30

    • Both conditions must hold for the computer to trigger the action "stay indoors".

    • Return qualification policy:

    • Expression: refund = (days < 30) or (damaged == True)

    • Scenario: An item returned at days = 21 with damaged = False.

    • Evaluation: 21 < 30 evaluates to True. Because True or False yields True, the refund is approved.

  • Logical Complements and De Morgan's Principles:

    • In discount qualification: Customers receive discounts if age < 12 or age > 65 (children and seniors).

    • Finding the inverse/complement condition for who does not receive a discount:

    • Complement of < is >=.

    • Complement of > is <=.

    • Complement of or is and.

    • The derived non-discount expression is: age >= 12 and age <= 65 (individuals between ages 12 and 65 inclusive).

  • Short-Circuit Evaluation:

    • Compound Boolean expressions evaluate from left to right.

    • The processor uses short-circuit evaluation to optimize execution speed:

    • In an and statement: If the left operand is False, the entire condition is definitively False; the runtime does not evaluate the right operand.

    • In an or statement: If the left operand is True, the entire condition is definitively True; the runtime does not evaluate the right operand.

    • Modulo Compound Expression Example:

    • Given variables A=9A = 9 and B=10B = 10.

    • Target expression: (A % 2 == 0 and ...) or (A % 2 == 1 and B % 2 == 0)

    • Left evaluation: A(mod2)=9(mod2)=1A \pmod 2 = 9 \pmod 2 = 1. The comparison 1 == 0 is False.

    • Short-circuit triggered: False and ... immediately resolves to False without computing the remaining part of the conjunction.

    • Right evaluation: A(mod2)=1A \pmod 2 = 1, so 1 == 1 is True. B(mod2)=10(mod2)=0B \pmod 2 = 10 \pmod 2 = 0, so 0 == 0 is True. Therefore, True and True evaluates to True.

    • Final resolution: False or True resolves to True.

  • The not Operator:

    • A unary operator that accepts exactly one operand and negates/inverts its truth value.

    • Rules:

    • not True →\rightarrow False

    • not False →\rightarrow True

    • Examples:

    • Given X=13X = 13, evaluate not (X < 10):

      • 13<1013 < 10 evaluates to False.

      • not False evaluates to True.

    • Negating an active variable condition:

      • Given is_turn = False and timer > 60 where timer is above 60:

      • timer > 60 evaluates to True.

      • not is_turn evaluates to not False, which is True.

      • Compound condition timer > 60 and not is_turn resolves to True and True, producing True.

Classroom Policies and Environment

  • Classroom Protocol and Etiquette:

    • Interactive participation is standard, but side conversations, whispering, and ambient noise disrupt learning during lecture periods.

    • Syllabus rules strictly require students to remove headphones and maintain silence while course content is being actively delivered.

    • The class duration is strictly 1 hour and 20 minutes, requiring continuous pacing and focused attention.

    • Lectures resume on the following Wednesday to continue control structures.

Questions and Classroom Interactions

  • Query on Using Integers in Conditional Statements:

    • Question: Can an integer variable directly drive an if conditional check (e.g., checking if is_dessert: when is_dessert = 0)?

    • Response: Yes. Whenever a non-Boolean value (such as an integer) is placed into a conditional check, the interpreter implicitly converts it into a Boolean value. An integer value of 0 converts to False, while any non-zero integer converts to True, which is then evaluated by the conditional structure.

  • Query on Language Differences with C and C++ Typing:

    • Question: Discussion regarding variable declarations, working with variable dictionaries, and differences in Boolean handling in C/C++ versus Python.

    • Response: In languages like C and C++, variables traditionally adhere to explicit, declared types such as int, float, double, and char. Native primitive Boolean support was historically absent without dedicated header libraries, whereas Python dynamically types variables and inherently supports native bool objects.

  • Query on Floating-Point Numerical Comparisons (4 < 4.0):

    • Question: Why does 4 < 4.0 evaluate to False instead of causing a type mismatch error or evaluating to True?

    • Response: Python compares the actual mathematical values of numeric types across int and float. Because 44 and 4.04.0 are equal in magnitude, neither is less than the other; hence the less-than operator evaluates to False.

  • Query on Python Version Differences (Python 2.7 vs. Modern Python):

    • Question: Does older software like Python 2.7 handle cross-type comparisons differently than current versions?

    • Response: Modern, up-to-date Python versions have resolved legacy behaviors and enforce strict type rules, disallowing arbitrary cross-type comparisons (such as integers with strings) and raising clear runtime errors.