Chapter 3 reading Notes: Decision Structures and Boolean Logic
3.1 The if Statement
- Concept: The if statement creates a decision structure that allows a program to follow more than one path of execution. It executes one or more statements only when a Boolean expression is true.
- Control structures overview:
- A control structure dictates the order in which statements execute.
- The book has introduced the sequence structure (execute statements in the order they appear).
- Some problems require branching based on conditions, i.e., decision structures (selection structures).
- Simple decision structure (single alternative):
- In its simplest form, a specific action is performed only if a condition exists (tested).
- Flowchart concept: a diamond tests a true/false condition; if true, an action path is taken; if false, the action is skipped (Figure 3-1).
- In Python, the single alternative is implemented with the if statement.
- General format of the if statement in Python:
python
if condition:
statement
statement
...
- The first line is the if clause: begins with the word if, followed by a condition (an expression evaluated as True/False), then a colon. The subsequent block contains indented statements belonging to the if.
- Boolean expressions and relational operators:
- The if statement tests Boolean expressions (expressions that evaluate to True or False).
- Boolean expressions are often formed with relational operators.
- Relational operators include: greater than, less than, greater than or equal to, less than or equal to, equal to, not equal to.
- Relational operators (Python) and their meanings:
- > Greater than
- < Less than
- \geq Greater than or equal to
- \leq Less than or equal to
- == Equal to
- \neq Not equal to
- Examples:
- length > width checks if length is greater than width (true/false).
- length < width checks if length is less than width.
- Interactive Python reference: typing Boolean expressions evaluates to True/False in the interpreter.
- Equality and not-equality operators:
- The equality operator is two equals signs: == (not the assignment operator, which is a single equals sign).
- The not-equal-to operator is \neq.
- Example: a simple conditional with overtime-like logic
python
if sales > 50000:
bonus = 500.0
- If the condition is true, the assignment runs; otherwise, it is skipped.
- Figure/flow examples (conceptual):
- A single alternative decision structure can trigger actions only when a condition is true.
- Checkpoint 3.1 (conceptual questions):
- What is a control structure?
- What is a decision structure?
- What is a single alternative decision structure?
- What is a Boolean expression?
- What types of relationships can you test with relational operators?
- Write an if statement that assigns 0 to x if y is equal to 20.
- Write an if statement that assigns 0.2 to commissionRate if sales is greater than or equal to 10000.
- Spotlight: "test_average.py" example (high score congratulation):
- Pseudocode:
- Get three test scores
- Calculate average
- Display the average
- If the average is greater than 95, congratulate the user
- Code fragment reference:
python
HIGH_SCORE = 95
# Get the three test scores...
# Calculate the average
average = (test1 + test2 + test3) / 3
print('The average score is', average)
if average >= HIGH_SCORE:
print('Congratulations!')
print('That is a great average!')
3.2 The if-else Statement
- Concept: The if-else statement provides a dual alternative decision structure: one block executes if the condition is true, another block executes if the condition is false.
- General format:
python
if condition:
statement
statement
...
else:
statement
statement
...
- Behavior:
- The condition is tested; if true, the if-block runs and control jumps after the entire if-else statement.
- If false, the else-block runs, then control jumps after the if-else statement.
- Indentation guidelines (indentation is required to define blocks):
- Align the if and else clauses.
- Each clause is followed by a block of statements, which must be consistently indented.
- Example (temperature check):
python
if temperature < 40:
print("A little cold, isn't it?")
else:
print("Nice weather we're having.")
- Indentation diagrams illustrate how the blocks execute depending on the condition.
- Indentation and alignment visuals: Figure 3-7 demonstrates indentation consistency for an if-else statement.
- Spotlight: Payroll example (if-else): "autorepairpayroll.py"
- Conceptual algorithm: Get hours worked and hourly rate; if hours > 40, compute overtime pay; else compute regular pay.
- Named constants: BASEHOURS = 40, OTMULTIPLIER = 1.5
- Key calculations:
- Overtime hours = hours - BASE_HOURS
- Overtime pay = overtimehours * payrate * OT_MULTIPLIER
- Gross pay = BASEHOURS * payrate + overtimepay (if overtime) or grosspay = hours * pay_rate (else)
- Output example: "The gross pay is $800.00" or "$1,100.00" depending on input.
3.3 Comparing Strings
- Concept: Python allows string comparisons using relational operators, enabling decision structures based on string values.
- Equality and inequality with strings:
- Example: name1 = 'Mary', name2 = 'Mark'
python
if name1 == name2:
print('The names are the same.')
else:
print('The names are NOT the same.')
- Example: if month != 'October': print('This is the wrong time for Octoberfest!')
- Program 3-3 (password.py): compares a user-entered password to 'prospero'
python
password = input('Enter the password: ')
if password == 'prospero':
print('Password accepted.')
else:
print('Sorry, that is the wrong password.')
- Note: Case sensitivity matters here; future chapters cover case-insensitive comparisons.
- ASCII and string ordering:
- ASCII codes define the ordering of characters (e.g., 'A' < 'B', 'a' > 'Z' in ASCII order).
- Uppercase A–Z: 65–90; lowercase a–z: 97–122; digits 0–9: 48–57; space: 32.
- String comparisons are character-by-character, guided by ASCII codes.
- Example: if 'a' < 'b': print('The letter a is less than the letter b.')
- Example: Mary vs Mark similarity/difference is determined by ASCII codes for character-by-character comparison.
- Program 3-4 (sort_names.py) demonstrates sorting two names alphabetically with the < operator:
python
name1 = input('Enter a name (last name first): ')
name2 = input('Enter another name (last name first): ')
if name1 < name2:
print(name1)
print(name2)
else:
print(name2)
print(name1)
- Checkpoint 3.11 and 3.12: practice questions about string comparisons and ordering.
- String vs ASCII ordering nuances:
- Multi-character strings are compared lexicographically by their character codes; shorter strings may be considered smaller if common prefix matches (e.g., 'Hi' < 'High').
- Practical takeaway: string comparisons are case-sensitive unless stated otherwise.
3.4 Nested Decision Structures and the if-elif-else Statement
- Concept: To test more than one condition, nest decision structures or use the if-elif-else chain.
- Combining decision and sequence structures:
- A flowchart example (Figure 3-10) shows a decision structure with sequences before and after it.
- A sequence structure can be nested inside a decision structure, and decisions can be nested inside other decisions.
- Bank loan scenario (nested decisions):
- Two conditions for loan qualification: salary >= 30000 and yearsonjob >= 2
- Program 3-5 uses nested if statements to test salary first, then yearsonjob.
- Key constants: MINSALARY = 30000.0, MINYEARS = 2
- Code snippet reference (structure):
python
if salary >= MIN_SALARY:
if years_on_job >= MIN_YEARS:
print('You qualify for the loan.')
else:
print('You must have been employed for at least', MIN_YEARS, 'years to qualify.')
else:
print('You must earn at least $' + format(MIN_SALARY, ',.2f') + ' per year to qualify.')
- Indentation and alignment guidelines (Figure 3-13, 3-14):
- Else clauses must align with their matching if.
- Blocks must have consistent indentation to readability and Python syntax.
- The if-elif-else statement (Figure 3-15 and surrounding discussion):
- General format:
python
if condition1:
statement
elif condition2:
statement
elif condition3:
statement
else:
statement
- This structure can replace long chains of nested if-else for readability.
- It reduces complexity and horizontal wrapping compared to deep nesting.
- Example: Grading program logic using if-elif-else (Program 3-6 and 3-7)
- Nested version (Program 3-6) tests score against thresholds 90, 80, 70, 60, else F, using nested ifs.
- If-elif-else version (Program 3-7) uses a single if-elif-else chain with constants ASCORE = 90, BSCORE = 80, CSCORE = 70, DSCORE = 60.
- Program 3-7 demonstrates equivalent logic with a flatter structure:
python
if score >= A_SCORE:
print('Your grade is A.')
elif score >= B_SCORE:
print('Your grade is B.')
elif score >= C_SCORE:
print('Your grade is C.')
elif score >= D_SCORE:
print('Your grade is D.')
else:
print('Your grade is F.')
- Insert as many elif clauses as necessary; else handles the default case.
- Checkpoint 3.13: convert given code to an if-elif-else structure (e.g., convert a chain of if/else into if-elif-else).
3.5 Logical Operators
- Concept: Logical operators allow combining Boolean expressions to form compound expressions.
- Operators:
- and: both subexpressions must be true for the compound expression to be true.
- or: at least one subexpression must be true; the compound expression is true if any is true.
- not: unary operator that negates the truth value of a Boolean expression.
- Short-circuit evaluation:
- and: If the left side is false, Python does not evaluate the right side (short-circuits) because the whole expression will be false.
- or: If the left side is true, Python does not evaluate the right side (short-circuits) because the whole expression will be true.
- Truth tables (summarized):
- and: true only when both operands are true; otherwise false.
- or: true when at least one operand is true.
- not: negates the truth value.
- Examples:
python
if temperature < 20 and minutes > 12:
print('The temperature is in the danger zone.')
- Numeric range checks with and/or:
- Inside a range: x \ge 20 \land x \le 40
python
if x >= 20 and x <= 40:
print('The value is in the acceptable range.')
- Outside a range: x < 20 \lor x > 40
python
if x < 20 or x > 40:
print('The value is outside the acceptable range.')
- Important caution: a faulty example like x < 20 and x > 40 can never be true (logically impossible).
- Examples: loan qualifier programs using logical operators
- Program 3-5 uses and: salary >= MINSALARY and yearsonjob >= MINYEARS to require both conditions.
- Program 3-7 refactors to use a single and: if salary >= MINSALARY and yearsonjob >= MINYEARS: … else: …
- Another variation (Program 3-8) uses or: if salary >= MINSALARY or yearsonjob >= MINYEARS: …
- Checking numeric ranges with and/or (explicit guidance):
- Inside range: and is preferred; outside range: or is preferred.
3.6 Boolean Variables
- Concept: A Boolean variable can reference one of two values: True or False (bool type).
- Typical use: flags indicating whether a condition exists.
- Examples:
- hungry = True
- sleepy = False
- Flags in practice:
- Example: sales quota tracking
python
if sales >= 50000.0:
sales_quota_met = True
else:
sales_quota_met = False
- Later, test the flag without explicit comparison:
python
if sales_quota_met:
print('You have met your sales quota!')
- This is equivalent to: if salesquotamet == True: print(…)
- Checkpoints 3.20–3.21 address values of bools and the meaning of a flag variable.
3.7 Turtle Graphics: Determining the State of the Turtle
- Concept: The turtle graphics library provides functions to determine the turtle's state and conditionally perform actions.
- State information you can query: current location (x, y), heading, pen state (up/down), current color, etc.
- Location methods:
- turtle.xcor() for the X-coordinate
- turtle.ycor() for the Y-coordinate
- Note: This section introduces practical uses of decision structures to react to the turtle's state during drawings. (The transcript cuts off mid-section; this note captures the intended topics.)
Connections to prior material and real-world relevance
- Decision structures extend the basic sequence programs by enabling conditional logic that mirrors real-world decision making (e.g., overtime pay, loan qualification, password checks).
- Boolean logic (and, or, not) allows combining multiple conditions, enabling complex rule-based behavior common in applications, games, data validation, and user interfaces.
- Nested decisions and if-elif-else reduce complexity and improve readability when testing multiple conditions, compared to deeply nested if-else chains.
- String comparisons are essential for authentication, user input handling, and sorting/filtering data in real-world software.
- Understanding ASCII and case sensitivity helps in designing robust text processing and search features.
- Boolean expressions using relational operators:
- length > width
- length < width
- x \ge y
- x \le y
- x = = y (Note: display as x == y in Python, not as a single equals sign.)
- Ranges using and/or:
- Inside [a, b]: a \le x \le b
- Outside [a, b]: x < a \lor x > b
- Example:
- If x is in [20, 40]: x \ge 20 \land x \le 40