Chapter 3 Notes: Decision Structures and Boolean Logic

3.1 The If Statement

  • Concept

    • A decision structure (selection structure) that allows a program to take more than one path of execution.

    • The if statement executes one or more statements only when a Boolean expression is true.

    • In Python, this is visualized as a flowchart diamond: test a condition; if true, follow the action path; if false, skip.

  • Python syntax and general format

    • General form:

    • if condition:

      • statements

    • The condition is a Boolean expression evaluated as true or false.

    • A colon appears after the condition; the next line begins a block of statements, which must be indented.

  • Boolean expressions and relational operators

    • Boolean expressions test relationships or conditions to decide truth value.

    • Relational operators (Python): >, <, >=, <=, ==, != lue is determined by the relational relationship between operands.

  • Relational operators in Python (examples)

    • Example: length > width determines if length is greater than width.

    • Example: length < width determines if length is less than width.

  • Example interactive session ideas

    • Interactive prompts and evaluation of expressions (assignments and booleans) demonstrate true/false results for expressions like x > y, x == y, x != y.

  • Equality and inequality operators

    • The equals-equals operator == tests for equality.

    • The not-equals operator != tests for inequality.

    • Important distinction: the assignment operator in Python is a single equals sign =, while the equality test is ==.

  • Conditional example: if statement with numerical comparison

    • Example: if sales > 50000:
      bonus = 500

    • If the condition is true, the action (bonus assignment) is executed; otherwise, it is skipped.

  • Single alternative decision structure (single line) and readability

    • Python allows a single-line form:

    • if condition: statement

    • However, for readability in programs, use the indented block form.

  • Practical example: test average program (Program 3.1)

    • Algorithm: get three test scores, calculate average, print average, and if average is greater than a high score, print a congratulatory message.

    • High score constant (named constant) holds the threshold value for a high average. In the transcript, the high score constant is given as

    • ext{high extunderscore score} = 9589

    • Sample structure (described):

    • get test scores

    • average = (test1 + test2 + test3) / 3

    • print(average)

    • if average > high_score: print("Congratulations. That is a great average.")

  • One-line if statements: caveats

    • Useful for quick tests in shell, but not ideal for larger programs or readability.

  • 3.1 Checkpoint questions (noninteractive)

    • 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 zero to x if y == 20.

    • Write an if statement that assigns 0.2 to commission_rate if sales >= 10000.

3.2 The If Else Statement

  • Concept

    • An if/else statement provides two possible execution paths: one if the condition is true, another if it is false.

  • Syntax and formatting

    • General format:

    • if condition:

      • statements (executed if true)

    • else:

      • statements (executed if false)

    • Indentation: the if block and the else block must be aligned; each block is a consistently indented group.

  • Flow and control flow

    • If the condition is true: execute the if-block, then continue after the if/else construct.

    • If the condition is false: execute the else-block, then continue.

  • Example: simple temperature check (If/Else)

    • If temperature > 40: print("a little cold, visit it?")

    • Else: print("nice weather we're having")

  • Practical example: auto repair payroll (Program 3.2)

    • Two named constants used:

    • base_hours = 40

    • OT_multiplier = 1.5

    • Inputs: hoursworked (float), payrate (float)

    • Logic:

    • If hours > base_hours:

      • overtimehours = hours - basehours

      • overtimepay = overtimehours * payrate * OTmultiplier

      • grosspay = (basehours * payrate) + overtimepay

    • Else:

      • grosspay = hours * payrate

    • Output: print gross_pay in dollars

  • Nested and chained decision structures (loan qualifier example, Program 3.5)

    • Nested approach: test salary first, then test yearsonjob if salary condition is true.

    • Combined/compound condition: using and/or to simplify logic (Program 3 seven and 3 eight)

  • Indentation and alignment rules for nested if/else

    • Always align corresponding else with its matching if.

    • Keep blocks consistently indented to improve readability and debugging.

  • 3.2 Checkpoint questions

    • How does a dual alternative decision structure work?

    • What statement is used to write a dual alternative decision structure in Python?

    • When do statements after else execute in an if/else statement?

3.3 Comparing Strings

  • Concept

    • Python can compare strings using relational and equality operators, enabling decision structures that test string values.

  • Equality and inequality for strings

    • Example: name1 = "Mary"; name2 = "Mark"; if name1 == name2: print("names are the same") else: print("names are not the same")

  • Example: month comparison

    • If month == "October": print("This is the wrong time for Oktoberfest")

  • Program 3.3: password check (Program 3.3, password_pi)

    • Get a password from user; compare with the string Prospero

    • If password == "Prospero": print("Password accepted") else: print("Sorry. That is the wrong password.")

  • Case sensitivity

    • String comparisons are case sensitive; "Prospero" != "prospero" unless case-insensitive handling is used (Chapter 8 will cover this).

  • Other string comparisons and sorting

    • Strings can be compared with > or < for sorting purposes because character codes determine order.

    • ASCII encoding basics (Appendix C reference)

    • Uppercase A-Z: 65–90

    • Lowercase a-z: 97–122

    • Digits 0-9: 48–57

    • Space: 32

    • Strings are compared character by character from left to right until a difference is found or one string ends.

  • Example: Mary vs Mark

    • Compare 'M' with 'M' (same), compare 'a' with 'a' (same), 'r' with 'r' (same), 'y' with 'k' (y > k), so "Mary" > "Mark".

  • Program 3.4: sort two names alphabetically

    • Get two names from user: name1, name2

    • Print in alphabetical order: if name1 < name2: print(name1); print(name2) else: print(name2); print(name1)

  • 3.3 Checkpoint questions

    • What would a given code display for various string comparisons (e.g., with and without equals)?

    • How does a simple two-name alphabetical sort behave?

3.4 Nested Decision Structures in the Statement

  • Concept

    • You can nest decision structures inside others to test more than one condition.

    • A commonly shown pattern is a decision (outer) containing a sequence of steps (inner) or another nested decision.

  • Flow examples and visuals

    • A combined flowchart that includes an outer decision with a nested sequence, or a nested decision inside another decision.

  • Loan qualifier with nested decisions (salary and years on the job)

    • Outer test: salary >= 30,000

    • If true, test second condition: yearsonjob >= 2

    • If both true: qualifies; else: does not qualify (with explanations in more detailed versions)

  • Program 3.5: complete loan qualifier (nested version)

    • Salary and minimum years are read; if salary >= minsalary and yearsonjob >= minyears: print("I qualify for the loan") else: print("I do not qualify for this loan")

  • Indentation and readability in nested structures

    • Proper indentation and alignment are essential for human readability and to avoid logical errors.

  • Testing a series of conditions (10-grade example) (Program 3 six)

    • Nested decisions to assign grades A, B, C, D, F based on score ranges.

    • Use of named constants for thresholds (e.g., ascore = 90, bscore = 80, etc.).

  • The elif statement as a more readable alternative

    • The if/elif/else chain provides a linear, readable alternative to deep nesting.

  • Advantages of if/elif/else over deep nesting

    • Easier to read and debug; avoids excessive indentation; quotes are aligned; easier to maintain.

  • 3.4 Noninteractive checkpoint questions

    • Convert nested if/else blocks to equivalent structures using elif.

    • Explain why using elif improves readability over deep nesting.

3.5 Logical Operators

  • Concept

    • Logical operators connect Boolean expressions to form compound expressions:

    • and: true only if both sub-expressions are true.

    • or: true if at least one sub-expression is true.

    • not: negates a Boolean expression.

  • Short-circuit evaluation

    • And: if the left side is false, the right side is not evaluated (short-circuited).

    • Or: if the left side is true, the right side is not evaluated (short-circuited).

  • Truth tables (high-level)

    • And: true only if both sides are true; otherwise false.

    • Or: true if at least one side is true; false only if both are false.

    • Not: inverts the truth value.

  • Notation examples

    • If temperature < 20 and temperature > 12: print("temperature is in danger zone")

    • If temperature < 20 or temperature > 100: print("temperature is extreme")

  • Range checks using logical operators

    • Inside range: x ext{ >= } 20 ext{ and } x ext{ <= } 40

    • Outside range: x < 20 ext{ or } x > 40

  • Common pitfall: using and instead of or (inside/outside ranges) can lead to always-false conditions

    • Correct form for “outside range” uses or; using and would be logically incorrect.

  • Examples: compound loan qualifier with and/or (Program 3 seven and 3 eight)

    • Old: salary >= minsalary and yearsonjob >= minyears (and)

    • New with or: salary >= minsalary or yearsonjob >= minyears (to allow qualification if either condition is met, depending on the rule)

  • 3.5 Noninteractive checkpoint questions

    • Explain how an and/or/not compound expression behaves.

    • Given a numeric range, write an expression to test inside or outside the range using and/or.

3.6 Boolean Variables

  • Concept

    • bool is a data type with two possible values: True and False.

    • Used as flags to indicate whether a condition exists (e.g., quota met: True/False).

  • Example

    • salesquotamet = (sales == 50000)

    • Later: if salesquotamet: print("I have met your sales quota")

  • True/False tests vs explicit comparison

    • The flag can be tested directly (if flag: …) without comparing to True.

  • 3.6 Noninteractive checkpoint questions

    • What values can a Boolean variable hold?

    • What is a flag, and how does it work?

3.7 Conditional Expressions

  • Concept

    • Also called the ternary operator: a short form of an if/else that yields a value.

    • General format: value1 ext{ if } condition ext{ else } value2

  • How it works

    • If condition is true, the expression yields value1; otherwise, it yields value2.

  • Example

    • ext{grade} = ext{pass} ext{ if } ext{score} > 59 ext{ else } ext{fail}

  • Program 3.9: conditional expression example

    • A program that reads two numbers and assigns the larger to max using a conditional expression.

    • Example:

    • max = num1 if num1 > num2 else num2

    • print("The bigger number is", max)

  • 3.7 Noninteractive checkpoint questions

    • Explain the syntax and use cases of conditional expressions.

3.8 Assignment Expressions in the Walrus Operator

  • Concept

    • The walrus operator := creates an assignment expression: it assigns and returns the value in the same expression.

    • It allows embedding assignment inside larger expressions or function calls.

  • Syntax and example

    • Basic assignment: result := 27 (some languages style; in Python it's result = 27 and the walrus is used in expressions as x := 5 but Python usage is typically:

    • if (pay := hourspayrate) > 40:
      print("I worked overtime")

    • The assignment expression returns the value that was assigned, so it can be used in a larger statement.

  • Precedence and parentheses

    • The walrus operator has the lowest precedence of Python operators.

    • When combining with other operators, wrap the assignment expression in parentheses to ensure correct binding.

  • Example explanations

    • Pay test example: pay = hourspayrate; if pay > 40: print("I worked overtime") is equivalent to using a parenthesized assignment expression inside the condition.

  • Important notes

    • An assignment expression is not a standalone statement; it must be part of a larger statement.

  • 3.8 Review points (tips)

    • When using walrus operator in a condition with multiple operators, use parentheses for clarity and correctness.

3.9 Turtle Graphics (state of the turtle)

  • Topic reference

    • This section is listed as a topic, but the transcript does not provide detailed content.

    • Expected coverage would include querying and manipulating the turtle state (position, heading, pen status, etc.) and how to respond to its state in conditional logic.

Additional notes and cross-cutting concepts

  • ASCII and string ordering

    • Character codes drive string comparisons; uppercase letters come before lowercase in ASCII order, and digits and space have their own ranges.

    • Practical implication: string comparisons follow lexical ordering based on character codes, not linguistic dictionary order without normalization.

  • Short-circuit evaluation (summary)

    • For A and B: if A is false, B is not evaluated.

    • For A or B: if A is true, B is not evaluated.

  • Nested vs chained conditionals

    • Nested ifs can express complex multi-step decisions but can be hard to read.

    • elif/else chains (the statement form) provide a clearer, flatter structure for multiple mutually exclusive conditions.

  • Key takeaways for exam prep

    • Distinguish between sequence (no conditions) and decision structures (if, if/else, if/elif/else).

    • Be able to construct and read a single-alternative (if) and dual-alternative (if/else) decision structure.

    • Use relational operators to form Boolean expressions; understand string comparisons and ASCII ordering.

    • Apply logical operators (and, or, not) and understand short-circuit evaluation.

    • Use conditional expressions for concise value selection; understand the walrus operator for assignment expressions and its precedence rules.

    • Recognize common programming patterns: including loan qualifiers, grade determination, test score processing, and simple payroll rules.

Key formulas and LaTeX-ready expressions

  • Relational operators (Python): >, <, \ge, \le, ==, \ne

  • Example relational expression: length > width or length < width

  • ASCII character ranges (memory/storage and ordering)

    • Uppercase: 65, 66, \dots, 90

    • Lowercase: 97, 98, \dots, 122

    • Digits: 48, 49, \dots, 57

    • Space: 32

  • Conditional expression syntax: value1\ if\ condition\ else\ value2

  • Bounds for range checks (examples):

    • Inside: x\ge 20\ \land\ x\le 40

    • Outside: x<20\ \lor\ x>40

  • Example of a simple if/else structure (conceptual):

    • if\ condition:\n\t statements\nelse:\n\t other_statements

  • Walrus operator usage (conceptual):

    • if\ (pay := hours extunderscore pay extunderscore rate) > 40:\n\t print(x)

  • Boolean expression with and/or/not (conceptual truth tables):

    • And: both True → True; otherwise False

    • Or: at least one True → True; otherwise False

    • Not: negate truth value

End of notes for Chapter 3 topics.