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:
YesorNo(orTrueorFalse).Branching behavior example:
Query inside diamond: "Is it raining?"
If outcome is
True(): The flow directs to an action such as "Take an umbrella".If outcome is
False(): 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:
TrueorFalse.Syntax requirement: In Python,
TrueandFalsemust always be written with an initial capital letter (TandF). 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 = 0evaluates to<class 'int'>.is_dessert = Falseevaluates to<class 'bool'>.Reassignment side effect: Reassigning
is_dessert = 0dynamically modifies the type ofis_dessertfrom<class 'bool'>to<class 'int'>.
Language-Level Differences (Python vs. C/C++):
Python contains an inherent, built-in primitive
booldata type.Traditional C does not feature an intrinsic, native Boolean type in the same manner without importing specific libraries, relying instead on integer primitives ( 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 toTruefor almost all values, with strictly defined exceptions.Falsy Values: The function returns
Falseexclusively when supplied with:Numerical zero values:
0,0.0,0.000Empty collection or string structures:
""(an empty string containing zero characters)Specific null/empty primitives.
Evaluation of Conversion Exercises:
bool(0.000)yieldsFalsebecause the underlying value evaluates numerically to zero.bool(-1)yieldsTruebecause any non-zero integer evaluates to true.bool("")yieldsFalsedue to being an empty string.bool("...")(a string containing punctuation or symbols) yieldsTruebecause the string is non-empty.bool(str_returning_function())yieldsTrueas long as the output is a non-empty string sequence.Sensitivity: Altering
0.000to a non-zero float such as0.1immediately causesbool(0.1)to returnTrue.
Converting Booleans to Other Data Types:
Converting Boolean states to numeric types evaluates according to binary definitions (, ):
int(True)yields1int(False)yields0float(True)yields1.0float(False)yields0.0Converting 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 (
TrueorFalse).
The Six Relational Operators:
==(Equal to): Evaluates if two operands have identical values (e.g.,2 == 2isTrue;2 == 3isFalse;'A' == 'a'isFalse). Requires two consecutive equal signs without intervening spaces.!=(Not equal to): Evaluates if two operands possess different values (e.g.,'A' != 'a'isTrue).<(Less than): Evaluates if the left operand is strictly smaller than the right (e.g.,2 < 3isTrue).>(Greater than): Evaluates if the left operand is strictly larger than the right (e.g.,2 > 3isFalse).<=(Less than or equal to): Evaluates if the left operand is smaller than or equal to the right (e.g.,2 <= 3isTrue).>=(Greater than or equal to): Evaluates if the left operand is larger than or equal to the right (e.g.,2 >= 3isFalse).
Evaluation Mechanics and Type Rules:
Given : The expression
compareResult = (X <= 13)evaluates14 <= 13, yieldingFalse, which is stored incompareResult.Mixed Numeric Comparisons: Evaluating
4 < 4.0returnsFalse. The interpreter compares numeric values directly across numerical types (intandfloat); since is mathematically equal to , 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 ( through ) precede lowercase letters.
Uppercase corresponds to ASCII value .
Uppercase corresponds to ASCII value .
Lowercase letters ( through ) possess larger numerical values, starting at and extending past .
Consequently, any lowercase character is strictly greater than any uppercase character in an ASCII comparison (e.g.,
'a' > 'A'isTrue).
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 toFalse(109 students selected false in lecture poll)."Cat" vs. "cat":
Comparing index : uppercase
'C'vs. lowercase'c'.Because lowercase characters possess higher ASCII indices than uppercase characters,
'c' > 'C'.Thus,
"cat" > "Cat"isTrue."cat" vs. "cats":
Characters at index , , and are identical (
'c','a','t').The string
"cat"terminates with a null character (), whereas"cats"contains's'at index .Thus,
"cats" > "cat"evaluates toTrue."cilantro" vs. "coriander":
Index matches (
'c' == 'c').Index compares
'i'with'o'. Because'o'succeeds'i'alphabetically and numerically in ASCII,'o' > 'i'.Thus,
"coriander" > "cilantro"evaluates toTrue.
Boolean Logical Operators
Overview of Logical Operators:
Alongside the 6 relational operators, programming relies on 3 logical Boolean operators:
and,or, andnot(providing 9 total decision operators).
The
andOperator:A binary operator requiring two Boolean operands (left and right).
Both operands must evaluate to
Truefor the compound expression to yieldTrue.Truth Table for
and:True and TrueTrueTrue and FalseFalseFalse and TrueFalseFalse and FalseFalseReal-world analogy: A joint bank account requiring an "AND" mandate requires both account holders to be present simultaneously to authorize a withdrawal.
The
orOperator:A flexible binary operator requiring only one operand to evaluate to
Trueto yield a result ofTrue.Evaluates to
Falseexclusively when both operands areFalse.Truth Table for
or:True or TrueTrueTrue or FalseTrueFalse or TrueTrueFalse or FalseFalseReal-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.30Both 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 = 21withdamaged = False.Evaluation:
21 < 30evaluates toTrue. BecauseTrue or FalseyieldsTrue, 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
orisand.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
andstatement: If the left operand isFalse, the entire condition is definitivelyFalse; the runtime does not evaluate the right operand.In an
orstatement: If the left operand isTrue, the entire condition is definitivelyTrue; the runtime does not evaluate the right operand.Modulo Compound Expression Example:
Given variables and .
Target expression:
(A % 2 == 0 and ...) or (A % 2 == 1 and B % 2 == 0)Left evaluation: . The comparison
1 == 0isFalse.Short-circuit triggered:
False and ...immediately resolves toFalsewithout computing the remaining part of the conjunction.Right evaluation: , so
1 == 1isTrue. , so0 == 0isTrue. Therefore,True and Trueevaluates toTrue.Final resolution:
False or Trueresolves toTrue.
The
notOperator:A unary operator that accepts exactly one operand and negates/inverts its truth value.
Rules:
not TrueFalsenot FalseTrueExamples:
Given , evaluate
not (X < 10):evaluates to
False.not Falseevaluates toTrue.
Negating an active variable condition:
Given
is_turn = Falseandtimer > 60where timer is above 60:timer > 60evaluates toTrue.not is_turnevaluates tonot False, which isTrue.Compound condition
timer > 60 and not is_turnresolves toTrue and True, producingTrue.
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
ifconditional check (e.g., checkingif is_dessert:whenis_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
0converts toFalse, while any non-zero integer converts toTrue, 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, andchar. Native primitive Boolean support was historically absent without dedicated header libraries, whereas Python dynamically types variables and inherently supports nativeboolobjects.
Query on Floating-Point Numerical Comparisons (
4 < 4.0):Question: Why does
4 < 4.0evaluate toFalseinstead of causing a type mismatch error or evaluating toTrue?Response: Python compares the actual mathematical values of numeric types across
intandfloat. Because and are equal in magnitude, neither is less than the other; hence the less-than operator evaluates toFalse.
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.