Algorithmic Thinking with Python: Selection and Iteration

Course Curriculum & Foundations

  • Module 3 Subject Matter Scope:

    • Selection and Iteration Using Python: Evaluation of conditional execution using if, if-else, and multi-way elif statements; repetition structures including definite iteration via for loops and range(), conditional iteration via while loops, and loop control mechanisms (break, continue, pass).
    • Sequence Data Types in Python: Operations, mechanics, and structures of sequence types including list, tuple, set, strings, and dictionary; creation and manipulation of arrays using the numpy library.
    • Decomposition and Modularization: Problem decomposition strategies for dissecting complex engineering tasks; modular programming principles and their motivations; defining and invoking Python functions; syntax and applications of functions returning multiple values.
  • Foundational Perspective:

    • "Whether you want to uncover the secrets of the universe, or you just want to pursue a career in the 21st century, basic computer programming is an essential skill to learn." — Stephen Hawking.

Selection Statements: if and if-else

  • Core Concept of Selection:

    • Selection control statements allow a program to test conditions and branch into alternate execution paths based on whether a boolean expression evaluates to True or False.
  • Single-Way if Statements:

    • Syntax:python if <condition>: # body of if statement &nbsp;&nbsp;&nbsp;&nbsp;
  • Structural Rules:

    • The logical <condition> must be immediately followed by a colon (:).
    • The body beneath the if header must be indented.
    • Python standard conventions mandate a 44-space indentation level.
    • Every statement belonging to the same block must share the exact same indentation width.
  • Worked Example: ```python number = 10

    check if number is greater than 0

    if number > 0: print('Number is positive.')

    print('Statements outside if')     ```

  • Two-Way if-else Statements:

    • Syntax:python if <condition>: # block of code if condition is True else: # block of code if condition is False &nbsp;&nbsp;&nbsp;&nbsp;
  • Structural Rules:

    • The else keyword provides an alternate execution path when <condition> evaluates to False.
    • else must reside on its own line at the exact same indentation level as the corresponding if statement.
    • The else keyword must conclude with a colon (:).
    • Code within the else block must be indented uniformly (typically 44 spaces).
  • Worked Example: ```python number = 10

    if number > 0: print('Positive number') else: print('Negative number')

    print('This statement is always executed')     ```

Multi-Way Selection: if-elif-else Statements

  • Multi-Way Selection Mechanics:

    • Used when a program must evaluate multiple mutually exclusive conditions sequentially.
    • In Python, the keyword elif serves as the syntactic contraction for "else if".
    • Conditions are evaluated top-down; as soon as a condition evaluates to True, its corresponding block executes, and the remainder of the construct is skipped.
  • Syntax:

  if <condition1>:
      # code block 1
  elif <condition2>:
      # code block 2
  else:
      # code block 3
&nbsp;&nbsp;```

* **Grading Criteria Mapping Table:**
  * Letter Grade AA: All grades strictly above 8989 (Grade>89\text{Grade} > 89).
  * Letter Grade BB: All grades strictly above 7979 and below 9090 (79<Grade<9079 < \text{Grade} < 90).
  * Letter Grade CC: All grades strictly above 6969 and below 8080 (69<Grade<8069 < \text{Grade} < 80).
  * Letter Grade FF: All grades strictly below 7070 (Grade<70\text{Grade} < 70).

* **Sign-Checking Example:**

python number = 0

if number > 0: print("Positive number") elif number == 0: print('Zero') else: print('Negative number')

print('This statement is always executed')   ```

Selection Control Exercises & Solutions

  • Exercise 1: Even or Odd Number Checker:

    • Problem Description: Write a Python program prompting the user to enter an integer. Determine whether the number is even or odd, printing "The number <number> is even." or "The number <number> is odd.".
    • Solution:python number = int(input("Enter a number: ")) if number % 2 == 0: print("The number", number, "is even.") else: print("The number", number, "is odd.") &nbsp;&nbsp;&nbsp;&nbsp;
  • Exercise 2: Finding the Maximum of Two Numbers:

    • Problem Description: Write a program taking two numbers as user inputs and displaying the larger value. If both are identical, output "The numbers are equal.".
    • Solution: ```python num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: "))

    if num1 > num2: print(f"The larger number is {num1}.") elif num2 > num1: print(f"The larger number is {num2}.") else: print("The numbers are equal.")     ```

  • Exercise 3: Academic Grade Categorization:

    • Grading Scale Rules:
    • Marks≥90\text{Marks} \ge 90: Grade AA
    • Marks∈[80,89]\text{Marks} \in [80, 89]: Grade BB
    • Marks∈[70,79]\text{Marks} \in [70, 79]: Grade CC
    • Marks∈[60,69]\text{Marks} \in [60, 69]: Grade DD
    • Marks<60\text{Marks} < 60: Grade FF
    • Solution: ```python marks = int(input("Enter your marks: "))

    if marks >= 90: print("Grade: A") elif marks >= 80: print("Grade: B") elif marks >= 70: print("Grade: C") elif marks >= 60: print("Grade: D") else: print("Grade: F")     ```

  • Exercise 4: Vowel vs. Consonant Character Classifier:

    • Problem Description: Read a single character from the user. Verify whether it is alphabetic. If valid, check whether it is a vowel or a consonant. If non-alphabetic, output "Invalid input.".
    • Solution: ```python char = input("Enter a single character: ")

    Check if the input is a single alphabetic character

    if char.isalpha(): if char in 'AEIOUaeiou': # Check if the character is a vowel print(f"{char} is a vowel.") else: print(f"{char} is a consonant.") else: print("Invalid input.")     ```

  • Exercise 5: Leap Year Validation:

    • Logic Criteria:
    • If the year is divisible by 400400, it is a leap year.
    • If the year is divisible by 100100 but not by 400400, it is not a leap year.
    • If the year is divisible by 44 but not by 100100, it is a leap year.
    • All other years are not leap years.
    • Solution: ```python

    Program to check if a year is a leap year

    year = int(input("Enter a year: "))

    Check the conditions for a leap year

    if year % 400 == 0: print(f"{year} is a leap year.") elif year % 100 == 0: print(f"{year} is not a leap year.") elif year % 4 == 0: print(f"{year} is a leap year.") else: print(f"{year} is not a leap year.")     ```

  • Exercise 6: Password Strength Evaluator:

    • Classification Thresholds:
    • Length strictly less than 66 characters: "Weak"
    • Length between 66 and 1010 characters inclusive (6≤length≤106 \le \text{length} \le 10): "Medium"
    • Length strictly greater than 1010 characters: "Strong"
    • Solution: ```python password = input("Enter a password: ") length = len(password)

    if length < 6: print("Password strength: Weak") elif 6 <= length <= 10: print("Password strength: Medium") else: print("Password strength: Strong")     ```

Definite Iteration: for Loops & range()

  • Taxonomy of Loops:

    • Definite Iteration: Statements that execute a repetitive action a predetermined number of times (primarily handled by Python's for loop).
    • Indefinite Iteration: Statements that execute an action repeatedly until an external or computed condition signals termination (handled by while loops).
  • Structure of the for Loop:

    • General Syntax:python for <variable> in range(<an integer expression>): <statement-1> # ... <statement-n> &nbsp;&nbsp;&nbsp;&nbsp;
    • The line for <variable> in range(...): represents the loop header and terminates with a colon (:).
    • The indented block represents the loop body.
  • Parameters of the range() Function:

    • The range() function generates an immutable sequence of arithmetic integers, operating via three signatures:
    1. range(stop_value): Starts by default at 00, increments by 11, and terminates at stop_value−1\text{stop\_value} - 1.
    2. range(start_value, stop_value): Generates integers starting from start_value up to stop_value−1\text{stop\_value} - 1, incrementing by 11.
    3. range(start_value, stop_value, step_size): Generates integers beginning at start_value, incrementing by step_size on each step, stopping before stop_value.
  • Practical range() Examples:

    • Generating 00 through 55:python for i in range(6): print(i) # range(6) generates numbers 0, 1, 2, 3, 4, 5 &nbsp;&nbsp;&nbsp;&nbsp;
  • Generating 33 through 55:python for i in range(3, 6): print(i) # range(3, 6) generates numbers 3, 4, 5 &nbsp;&nbsp;&nbsp;&nbsp;

  • Generating Numbers with a Step Size (33 to 1919 stepping by 22):python for i in range(3, 20, 2): print(i) # Generates 3, 5, 7, 9, 11, 13, 15, 17, 19 &nbsp;&nbsp;&nbsp;&nbsp;

  • Negative Step Sizes (Counting Down):

    • When step_size is negative, range() decrements from start_value down to stop_value+1\text{stop\_value} + 1.
    • Example:python for count in range(10, 0, -1): print(count, end=" ") &nbsp;&nbsp;&nbsp;&nbsp;
    • Output: 10 9 8 7 6 5 4 3 2 1
  • Loop Output Comprehension Exercises:

    • Loop: for count in range(5): print(count + 1, end=" ")
    • Output: 1 2 3 4 5
    • Loop: for count in range(1, 4): print(count, end=" ")
    • Output: 1 2 3
    • Loop: for count in range(1, 6, 2): print(count, end=" ")
    • Output: 1 3 5
    • Loop: for count in range(6, 1, -1): print(count, end=" ")
    • Output: 6 5 4 3 2

Conditional Iteration: The while Loop

  • Structure and Behavior:

    • The while loop continues executing its code block as long as its controlling boolean expression evaluates to True.
    • Syntax:python while <condition>: <sequence of statements> &nbsp;&nbsp;&nbsp;&nbsp;
  • Execution Flowchart:

  Flowchart of a while loop showing conditional test and execution branch

  • Execution enters the conditional evaluation diamond (?).

  • If evaluated as true, the path leads directly into the statement block, which loops back to the condition diamond.

  • If evaluated as false, execution bypasses the body entirely and exits the loop construct downwards.

    • Comparison: Count Control via for vs. while:
  • Summation of Integers from 11 to 100,000100{,}000 using a for Loop:python theSum = 0 for count in range(1, 100001): theSum += count print(theSum) &nbsp;&nbsp;&nbsp;&nbsp;

    • Summation of Integers from 11 to 100,000100{,}000 using a while Loop:python theSum = 0 count = 1 while count <= 100000: theSum += count count += 1 print(theSum) &nbsp;&nbsp;&nbsp;&nbsp;

Loop Control Statements: break, continue, and pass

  • Overview:

    • Python provides three primary loop control statements to alter execution flow dynamically during iterations: break, continue, and pass.
  • The break Statement:

    • Causes immediate termination of the innermost enclosing loop, regardless of whether the loop test condition remains True.
    • Control jumps immediately to the statement directly following the loop body.
    • Example Finding the First Number Greater Than 55:python for num in range(1, 10): if num > 5: print(f"First number greater than 5 is: {num}") break # Exit loop immediately &nbsp;&nbsp;&nbsp;&nbsp;
    • Output: First number greater than 5 is: 6
  • The continue Statement:

    • Skips all remaining instructions inside the current iteration of the loop.
    • Rather than exiting the entire loop like break, it returns execution to the top of the loop for the next iteration.
    • Example Printing Odd Numbers Only:python for num in range(1, 10): if num % 2 == 0: continue # Skip even numbers print(num) &nbsp;&nbsp;&nbsp;&nbsp;
  • Output: text 1 3 5 7 9 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The pass Statement:

    • A null operation that serves as a syntactic placeholder.
    • Used when Python grammar mandates the presence of an indented block, but no functional instructions are needed at that time.
    • Prevents compilation and indentation errors without altering program behavior.
    • Example: ```python num = int(input("Enter a number: "))

    if num > 0: print(f"{num} is positive.") elif num < 0: print(f"{num} is negative.") else: pass # Placeholder for zero condition to be implemented later

    print("This message will always print after the condition checks.")     ```

  • Execution with input 10: text Enter a number: 10 10 is positive. This message will always print after the condition checks. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Execution with input 0: text Enter a number: 0 This message will always print after the condition checks. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Comparative Distinctions: pass vs. continue:

    • Core Functionality:
    • pass: Does nothing; serves as an empty code block placeholder.
    • continue: Abruptly aborts the remainder of the current loop iteration and moves execution to the subsequent loop cycle.
    • Primary Use Case:
    • pass: Utilized when establishing code stubs or scaffolding that has yet to be implemented.
    • continue: Utilized to filter out, ignore, or bypass specific values or conditions within a loop iteration.
    • Runtime Behavior:
    • pass: Code statements directly below pass within the same block continue normal linear execution.
    • continue: Statements directly below continue within the same iteration are completely skipped.

Iteration Exercises & Implementations

  • Exercise 1: Printing Numbers 11 to 1010 with while:

    • Implementation: ```python

    Initialize the counter

    num = 1

    Using a while loop to print numbers from 1 to 10

    while num <= 10: print(num) num += 1 # Increment the counter     ```

  • Exercise 2: Sum of First NN Natural Numbers:

    • Problem Description: Calculate the sum ∑i=1Ni\sum_{i=1}^{N} i for a user-specified integer NN using a for loop.
    • Implementation: ```python

    Input: Take the value of N from the user

    N = int(input("Enter a positive integer N: "))

    Initialize the sum

    total_sum = 0

    Using a for loop to calculate the sum

    for i in range(1, N + 1): total_sum += i # Add the current number to the sum

    print(f"The sum of the first {N} natural numbers is {total_sum}.")     ```

  • Exercise 3: Factorial Calculation using while:

    • Problem Description: Calculate num!=num×(num−1)×⋯×1num! = num \times (num - 1) \times \dots \times 1 for a user input using a while loop.
    • Implementation: ```python

    Input: Take the value from the user

    num = int(input("Enter a positive integer: "))

    Initialize the factorial result

    factorial = 1

    Using a while loop to calculate factorial directly with num

    while num > 1: factorial *= num # Multiply the result by the current number num -= 1 # Decrease num itself

    print(f"The factorial is {factorial}.")     ```

Random Number Generation & Application Case Study

  • Python random Module:

    • Offers functions for pseudo-random number generation.
    • random.randint(a, b): Returns a uniformly distributed pseudo-random integer NN such that a≤N≤ba \le N \le b (inclusive of both endpoints).
    • Example Simulating Die Rolls (1010 rolls of a 66-sided die): ```python import random

    for roll in range(10): print(random.randint(1, 6), end=" ")     ```

    • Representative Output: 2 4 6 4 3 2 3 6 2 2
  • Case Study: High-Low Number Guessing Game:

    • Functional Requirements:
    • The program prompts the user to define an inclusive range by entering the smaller and larger bounds.
    • The system selects a secret integer within this range using random.randint(smaller, larger).
    • An indefinite loop prompts the user to submit guesses.
    • For each guess, the system evaluates the value and prints "Too small!" or "Too large!".
    • Upon entering the correct value, the loop terminates, congratulating the user and displaying the total number of attempts.
    • Full Implementation: ```python import random

    smaller = int(input("Enter the smaller number: ")) larger = int(input("Enter the larger number: "))

    myNumber = random.randint(smaller, larger) count = 0

    while True: count += 1 userNumber = int(input("Enter your guess: ")) if userNumber < myNumber: print("Too small!") elif userNumber > myNumber: print("Too large!") else: print("Congratulations! You've got it in", count, "tries!") break     ```

External References

  • FreeCodeCamp Python Range Guide: https://www.freecodecamp.org/news/python-range-function-example/
  • W3Schools Python Range Reference: https://www.w3schools.com/python/ref_func_range.asp