Decision Structures, Boolean Logic, and Repetition in Python

The if Statement and Decision Structures

  • Decision Structure Concept: The if statement is used to create a decision structure, which allows a program to have more than one path of execution. It causes one or more statements to execute only when a Boolean expression is true.
  • Control Structure: A control structure is a logical design that controls the order in which a set of statements execute.
  • Sequence Structure: This is a set of statements that execute in the order in which they appear from top to bottom. Example:
    • name = input('What is your name? ')
    • age = int(input('What is your age? '))
    • print('Name:', name)
  • Limitations of Sequence Structures: Some problems require executing statements only under certain circumstances. For example, a payroll program calculating overtime only if hours worked exceed 4040.
  • Selection Structures: Decision structures are also known as selection structures. In their simplest form, an action is performed only if a specific condition exists. If the condition does not exist, the action is skipped.
  • Flowcharting Decision Structures:
    • The diamond symbol represents a true/false condition.
    • If the condition is true, one path is followed to an action.
    • If the condition is false, a different path is followed that skips the action.
  • Single Alternative Decision Structure: This provides exactly one alternative path of execution. If the condition is true, the path is taken; otherwise, the structure exits.
  • Python if Statement General Format:
    • if condition:
    • statement
    • statement
    • etc.
  • The if Clause: The first line of an if statement. It starts with the word if, followed by a condition (evaluated as True or False) and ends with a colon (:).
  • Blocks: A block is a set of statements that belong together as a group. In Python, blocks are defined by indentation. Consistent indentation is required for the interpreter to identify where a block begins and ends.

Boolean Expressions and Relational Operators

  • Boolean Expressions: Named after George Boole, these express computations using the abstract concepts of True and False.
  • Relational Operators: These determine whether a specific relationship exists between two values.
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
    • Equal to: == (Note: use two equals signs, not one)
    • Not equal to: !=
  • Examples of Boolean Logic (Let x = 1, y = 0, z = 1):
    • x > y is True.
    • y > x is False.
    • x >= z is True.
    • x == z is True.
    • x != y is True.
  • Equality vs. Assignment: Do not confuse the equality operator (==) with the assignment operator (=).

The if-else Statement

  • Dual Alternative Decision Structure: An if-else statement provides two possible paths: one for when the condition is true, and one for when it is false.
  • General Format:
    • if condition:
    • statement(s)
    • else:
    • statement(s)
  • Execution Logic: If the condition is true, the if-block executes and the else-block is ignored. If the condition is false, the if-block is skipped and the else-block executes. In both cases, program control then jumps to the statement following the if-else structure.
  • Indentation Guidelines: The if and else clauses must be aligned. The blocks following them must be consistently indented.

Comparing Strings

  • String Equality: The == and != operators can compare string values (e.g., name1 == name2).
  • Case Sensitivity: String comparisons are case sensitive. 'saturday' is not equal to 'Saturday' because of the lowercase vs. uppercase 's'.
  • ASCII and Character Ordering: Computers store characters as numeric codes using systems like ASCII (American Standard Code for Information Interchange).
    • 'A' through 'Z' are 6565 through 9090.
    • 'a' through 'z' are 9797 through 122122.
    • '0' through '9' are 4848 through 5757.
    • A blank space is 3232.
  • Greater Than / Less Than with Strings: Comparisons are done character-by-character based on ASCII values.
    • Example: 'Mary' vs 'Mark'.
      1. 'M' == 'M'
      2. 'a' == 'a'
      3. 'r' == 'r'
      4. 'y' (ASCII 121121) is greater than 'k' (ASCII 107107). Therefore, 'Mary' > 'Mark' is True.
  • String Length: If corresponding characters are identical but one string is shorter, the shorter string is considered less than the longer string (e.g., 'Hi' < 'High').

Nested Decision Structures and if-elif-else

  • Nested Decisions: A decision structure can be placed inside another decision structure to test multiple conditions.
  • Alignment Rules: Each else clause must align with its matching if. Indentation must remain consistent for each block.
  • The if-elif-else Statement: This provides a cleaner way to write logic with many alternatives, replacing deeply nested if-else structures.
  • General Format:
    • if condition_1:
    • statement
    • elif condition_2:
    • statement
    • else:
    • statement
  • Benefits of if-elif-else:
    • Reduces complex indentation and horizontal scrolling during debugging.
    • Stops testing conditions as soon as one is found to be True.

Logical Operators

  • Functional Definitions:
    • and: Connects two expressions; both must be True for the compound expression to be True.
    • or: Connects two expressions; only one (or both) must be True for the compound expression to be True.
    • not: A unary operator that reverses the truth of its operand (True becomes False; False becomes True).
  • Truth Tables:
    • and:
      • True and True = True
      • True and False = False
      • False and True = False
      • False and False = False
    • or:
      • True or True = True
      • True or False = True
      • False or True = True
      • False or False = False
  • Short-Circuit Evaluation:
    • For and: If the left operand is False, the right is not checked because the result must be False.
    • For or: If the left operand is True, the right is not checked because the result must be True.
  • Numeric Range Checking:
    • To check if a value is inside a range, use and: if x >= 20 and x <= 40:
    • To check if a value is outside a range, use or: if x < 20 or x > 40:

Boolean Variables

  • bool Data Type: Python variables can reference one of two values: True or False.
  • Flags: A flag is a Boolean variable used to signal whether a specific condition exists (e.g., sales_quota_met = True).
  • Testing Flags: You can test a flag directly: if flag: is equivalent to if flag == True:.

Introduction to Repetition Structures

  • Repetition Structure (Loop): Causes a statement or set of statements to execute repeatedly.
  • Advantages: Reduces code size, saves time, and makes maintenance easier (corrections only need to be made once).
  • Categories of Loops:
    • Condition-Controlled Loop: Uses a True/False condition to control repetition (Python while statement).
    • Count-Controlled Loop: Repeats a specific number of times (Python for statement).

The while Loop

  • Logic: While a condition is true, perform a task. If the condition is false, exit the loop.
  • Pretest Loop: The while loop tests its condition before performing an iteration. If the condition is false at the start, it will not execute at all.
  • Iteration: Each execution of the body of a loop.
  • Infinite Loops: If a loop does not have a way to make the test condition false, it repeats indefinitely. This is usually a logic error. To stop an infinite loop in some environments, use Ctrl+C.

The for Loop

  • Sequence Processing: Designed to iterate once for each item in a sequence (e.g., a list of values).
  • General Format: for variable in [value1, value2, etc.]:
  • Target Variable: The variable in the for clause that is assigned the value of the current item at the start of each iteration.
  • The range Function: Generates an iterable sequence of integers.
    • range(5) yields 0,1,2,3,40, 1, 2, 3, 4.
    • range(1, 5) yields 1,2,3,41, 2, 3, 4.
    • range(1, 10, 2) where 22 is the step value, yields 1,3,5,7,91, 3, 5, 7, 9.
    • range(10, 0, -1) yields 10,9,8,7,6,5,4,3,2,110, 9, 8, 7, 6, 5, 4, 3, 2, 1.

Calculating Running Totals and Sentinels

  • Accumulator: A variable used to keep a running total. It must be initialized (usually to 00 or 0.00.0) before the loop starts.
  • Augmented Assignment Operators: Shorthand for updating variables.
    • +=: x += 5 is x = x + 5
    • -=: y -= 2 is y = y - 2
    • *=: z *= 10 is z = z * 10
    • /=: a /= b is a = a / b
    • %=: c %= 3 is c = c % 3
  • Sentinels: A special value that marks the end of a sequence of items. It signals the loop to terminate without requiring the user to know the list length in advance (e.g., using 00 to end a list of positive numbers).

Input Validation

  • GIGO (Garbage In, Garbage Out): Refers to the fact that programs produce bad output if they process bad input.
  • Input Validation Loop: Inspects data before processing. If data is invalid, the loop prompts the user for correct values until the data is valid.
  • Priming Read: The first input operation performed before the validation loop to get the initial value for testing.

Nested Loops

  • Definition: A loop inside another loop.
  • Execution Logic: The inner loop completes all its iterations for every single iteration of the outer loop.
  • Clock Analogy:
    • Hours (Outer loop)
    • Minutes (Middle loop)
    • Seconds (Inner loop)
  • Calculation: Total iterations = (iterations of outer loop) ×\times (iterations of inner loop).
  • Pattern Printing Applications:
    • Rectangles: Outer loop handles rows; inner loop handles columns.
    • Triangles: Inner loop range depends on the current iteration of the outer loop (e.g., range(r + 1)).
    • Stair-steps: Use an inner loop to print spaces followed by a character to create an offset effect.