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-wayelifstatements; repetition structures including definite iteration viaforloops andrange(), conditional iteration viawhileloops, and loop control mechanisms (break,continue,pass). - Sequence Data Types in Python: Operations, mechanics, and structures of sequence types including
list,tuple,set, strings, anddictionary; creation and manipulation of arrays using thenumpylibrary. - 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.
- Selection and Iteration Using Python: Evaluation of conditional execution using
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
TrueorFalse.
- Selection control statements allow a program to test conditions and branch into alternate execution paths based on whether a boolean expression evaluates to
Single-Way
ifStatements:- Syntax:
python if <condition>: # body of if statement
- Syntax:
Structural Rules:
- The logical
<condition>must be immediately followed by a colon (:). - The body beneath the
ifheader must be indented. - Python standard conventions mandate a -space indentation level.
- Every statement belonging to the same block must share the exact same indentation width.
- The logical
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-elseStatements:- Syntax:
python if <condition>: # block of code if condition is True else: # block of code if condition is False
- Syntax:
Structural Rules:
- The
elsekeyword provides an alternate execution path when<condition>evaluates toFalse. elsemust reside on its own line at the exact same indentation level as the correspondingifstatement.- The
elsekeyword must conclude with a colon (:). - Code within the
elseblock must be indented uniformly (typically spaces).
- The
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
elifserves 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
```
* **Grading Criteria Mapping Table:**
* Letter Grade : All grades strictly above ().
* Letter Grade : All grades strictly above and below ().
* Letter Grade : All grades strictly above and below ().
* Letter Grade : All grades strictly below ().
* **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.")
- Problem Description: Write a Python program prompting the user to enter an integer. Determine whether the number is even or odd, printing
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.") ```
- Problem Description: Write a program taking two numbers as user inputs and displaying the larger value. If both are identical, output
Exercise 3: Academic Grade Categorization:
- Grading Scale Rules:
- : Grade
- : Grade
- : Grade
- : Grade
- : Grade
- 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.") ```
- 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
Exercise 5: Leap Year Validation:
- Logic Criteria:
- If the year is divisible by , it is a leap year.
- If the year is divisible by but not by , it is not a leap year.
- If the year is divisible by but not by , 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 characters:
"Weak" - Length between and characters inclusive ():
"Medium" - Length strictly greater than 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
forloop). - Indefinite Iteration: Statements that execute an action repeatedly until an external or computed condition signals termination (handled by
whileloops).
- Definite Iteration: Statements that execute a repetitive action a predetermined number of times (primarily handled by Python's
Structure of the
forLoop:- General Syntax:
python for <variable> in range(<an integer expression>): <statement-1> # ... <statement-n> - The line
for <variable> in range(...):represents the loop header and terminates with a colon (:). - The indented block represents the loop body.
- General Syntax:
Parameters of the
range()Function:- The
range()function generates an immutable sequence of arithmetic integers, operating via three signatures:
range(stop_value): Starts by default at , increments by , and terminates at .range(start_value, stop_value): Generates integers starting fromstart_valueup to , incrementing by .range(start_value, stop_value, step_size): Generates integers beginning atstart_value, incrementing bystep_sizeon each step, stopping beforestop_value.
- The
Practical
range()Examples:- Generating through :
python for i in range(6): print(i) # range(6) generates numbers 0, 1, 2, 3, 4, 5
- Generating through :
Generating through :
python for i in range(3, 6): print(i) # range(3, 6) generates numbers 3, 4, 5 Generating Numbers with a Step Size ( to stepping by ):
python for i in range(3, 20, 2): print(i) # Generates 3, 5, 7, 9, 11, 13, 15, 17, 19 Negative Step Sizes (Counting Down):
- When
step_sizeis negative,range()decrements fromstart_valuedown to . - Example:
python for count in range(10, 0, -1): print(count, end=" ") - Output:
10 9 8 7 6 5 4 3 2 1
- When
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
- Loop:
Conditional Iteration: The while Loop
Structure and Behavior:
- The
whileloop continues executing its code block as long as its controlling boolean expression evaluates toTrue. - Syntax:
python while <condition>: <sequence of statements>
- The
Execution Flowchart:

Execution enters the conditional evaluation diamond (
?).If evaluated as
true, the path leads directly into thestatementblock, 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
forvs.while:
- Comparison: Count Control via
Summation of Integers from to using a
forLoop:python theSum = 0 for count in range(1, 100001): theSum += count print(theSum) - Summation of Integers from to using a
whileLoop:python theSum = 0 count = 1 while count <= 100000: theSum += count count += 1 print(theSum)
- Summation of Integers from to using a
Loop Control Statements: break, continue, and pass
Overview:
- Python provides three primary loop control statements to alter execution flow dynamically during iterations:
break,continue, andpass.
- Python provides three primary loop control statements to alter execution flow dynamically during iterations:
The
breakStatement:- 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 :
python for num in range(1, 10): if num > 5: print(f"First number greater than 5 is: {num}") break # Exit loop immediately - Output:
First number greater than 5 is: 6
- Causes immediate termination of the innermost enclosing loop, regardless of whether the loop test condition remains
The
continueStatement:- 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)
Output:
text 1 3 5 7 9 The
passStatement:- 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. Execution with input
0:text Enter a number: 0 This message will always print after the condition checks. Comparative Distinctions:
passvs.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 belowpasswithin the same block continue normal linear execution.continue: Statements directly belowcontinuewithin the same iteration are completely skipped.
Iteration Exercises & Implementations
Exercise 1: Printing Numbers to 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 Natural Numbers:
- Problem Description: Calculate the sum for a user-specified integer using a
forloop. - 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}.") ```
- Problem Description: Calculate the sum for a user-specified integer using a
Exercise 3: Factorial Calculation using
while:- Problem Description: Calculate for a user input using a
whileloop. - 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}.") ```
- Problem Description: Calculate for a user input using a
Random Number Generation & Application Case Study
Python
randomModule:- Offers functions for pseudo-random number generation.
random.randint(a, b): Returns a uniformly distributed pseudo-random integer such that (inclusive of both endpoints).- Example Simulating Die Rolls ( rolls of a -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
smallerandlargerbounds. - 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