Loops & Iterations
Topic: Loops & Iterations (for & while)
Description: This section covers execution optimization, iterating across data sequences, and performing structural counters.
Why: Loops allow you to automate repetitive tasks and process collections of data efficiently. Mastering both fixed iterations (for loops) and conditional loops (while loops) is fundamental to building optimization algorithms and handling dynamic data structures.
Program 2.1: Sum of First N Natural Numbers
Problem Statement: Write a loop program that takes an integer N and computes the cumulative total of numbers ranging from 1 to N inclusive.
Expected Input & Output:
- Input:
5→ Output:15(1 + 2 + 3 + 4 + 5)
Core Syntax Hint: Use a for loop mapped alongside Python's native range(start, stop + 1) generator sequence to track a running accumulator value.
def sum_up_to_n(n): total_sum = 0 for i in range(1, n + 1): total_sum += i return total_sum # Test Case Execution / Output Example print(sum_up_to_n(5)) # Output: 15
Program 2.2: Multiplication Table Generator
Problem Statement: Generate a multiplication table array up to factor 10 for any given integer parameter input.
Expected Input & Output:
- Input:
3→ Output:["3 x 1 = 3", "3 x 2 = 6", ... "3 x 10 = 30"]
Core Syntax Hint: Leverage string interpolation formatting (f-strings) inside a standard loop matrix block to output nicely aligned structured strings.
def generate_table(number): results = [] for i in range(1, 11): results.append(f"{number} x {i} = {number * i}") return results # Test Case Execution / Output Example table_outputs = generate_table(3) for line in table_outputs: print(line) # Output: # 3 x 1 = 3 # 3 x 2 = 6 # ... up to 3 x 10 = 30
Program 2.3: Countdown Timer (While Loop)
Problem Statement: Create a script using a loop structure that counts backward from a starting integer value down to 1, and appends a completion string message at termination points.
Expected Input & Output:
- Input:
3→ Output:[3, 2, 1, "Blast off!"]
Core Syntax Hint: A while loop executes continuously as long as its condition remains True. Ensure you decrement the variable inside the block to prevent infinite execution loops.
def countdown(start): sequence = [] while start > 0: sequence.append(start) start -= 1 sequence.append("Blast off!") return sequence # Test Case Execution / Output Example print(countdown(3)) # Output: [3, 2, 1, 'Blast off!']
Program 2.4: Vowel Counter within a String
Problem Statement: Write a text parsing logic script that iterates through a string and returns a complete count of every vowel (a, e, i, o, u) present inside it.
Expected Input & Output:
- Input:
"skill eco"→ Output:3
Core Syntax Hint: Strings are iterables in Python. You can inspect characters one by one and use the membership operator (in) to check them against a reference string of vowels.
def count_vowels(text): vowel_count = 0 vowels = "aeiouAEIOU" for char in text: if char in vowels: vowel_count += 1 return vowel_count # Test Case Execution / Output Example print(count_vowels("skill eco")) # Output: 3
Program 2.5: Find Prime Numbers in a Range
Problem Statement: Write a robust utility that tracks down and isolates all prime numbers located within a user-specified numerical window.
Expected Input & Output:
- Input:
start=10, end=20→ Output:[11, 13, 17, 19]
Core Syntax Hint: Implement nested loop structures. The outer loop traverses the target numbers, while the inner loop verifies factors up to the square root of the number (num**0.5) for structural runtime optimization.
def find_primes(start, end): prime_list = [] for num in range(start, end + 1): if num > 1: is_prime = True for i in range(2, int(num**0.5) + 1): if num % i == 0: is_prime = False break if is_prime: prime_list.append(num) return prime_list # Test Case Execution / Output Example print(find_primes(10, 20)) # Output: [11, 13, 17, 19]
🏋️ Test Yourself With Exercises
Take our quiz on Loops & Iterations to test your knowledge.
Browse Quizzes »