Python for Loop Practice: 12 Core Problems with Solutions

Sharpen your iteration skills with 12 hands-on practice problems covering Python for loops, numerical stepping with range(), index tracking with enumerate(), and nested structures.

Structured Problem Set: Each challenge includes an interactive solution toggle, syntax-highlighted code, dedicated terminal output, and algorithmic notes. Compare definite iteration against indefinite while loops, manage early exits with break and continue, and run self-validating test assertions.

for item in iterable Has Next? Yes Assign item variable Execute loop body No else block or Exit Figure 1: Evaluation Flow & for-else Lifecycle

Part 1: Ranges & Traversal (Questions 1 to 3) 🔝

  1. Print the first 10 natural numbers (1 to 10) and calculate their sum.
    total = 0
    for i in range(1, 11):
        print(i, end=' ')
        total += i
    print(f'\nTotal Sum: {total}')

    Terminal Output:

    1 2 3 4 5 6 7 8 9 10
    Total Sum: 55
  2. Traverse a string character by character with formatting.
    word = 'Python'
    for ch in word:
        print(f'Char: {ch}')

    Terminal Output:

    Char: P
    Char: y
    Char: t
    Char: h
    Char: o
    Char: n
  3. Track both 1-based index and element values using enumerate().
    frameworks = ['Django', 'Flask', 'FastAPI']
    for idx, item in enumerate(frameworks, start=1):
        print(f'{idx}. {item}')

    Terminal Output:

    1. Django
    2. Flask
    3. FastAPI

Part 2: Step Increments & Mathematical Loops (Questions 4 to 6) 🔝

  1. Generate stepped ranges: even numbers up to 20 and countdown from 10.
    for val in range(2, 21, 2):
        print(val, end=' ')
    print()
    
    for num in range(10, 0, -1):
        print(num, end=' ')
    print()

    Terminal Output:

    2 4 6 8 10 12 14 16 18 20
    10 9 8 7 6 5 4 3 2 1
  2. Calculate the factorial of a positive integer N using a loop.
    num = 5
    factorial = 1
    for i in range(1, num + 1):
        factorial *= i
    print(f'{num}! =', factorial)

    Terminal Output:

    5! = 120
  3. Print a multiplication table up to 10.
    table_num = 7
    for i in range(1, 11):
        print(f'{table_num} x {i:>2} = {table_num * i:>2}')

    Terminal Output:

    7 x  1 =  7
    7 x  2 = 14
    7 x  3 = 21
    7 x  4 = 28
    7 x  5 = 35
    7 x  6 = 42
    7 x  7 = 49
    7 x  8 = 56
    7 x  9 = 63
    7 x 10 = 70

Part 3: Break, Continue & for...else (Questions 7 to 9) 🔝

  1. Linear search with early break on finding the target element.
    items = [10, 45, 88, 32, 99]
    target = 88
    for pos, x in enumerate(items):
        if x == target:
            print(f'Found {target} at index {pos}')
            break

    Terminal Output:

    Found 88 at index 2
  2. Filter out multiples of 3 in a range from 1 to 15 using continue.
    for n in range(1, 16):
        if n % 3 == 0:
            continue
        print(n, end=' ')
    print()

    Terminal Output:

    1 2 4 5 7 8 10 11 13 14
  3. Prime number verification using the for...else clause.
    candidate = 17
    for d in range(2, int(candidate ** 0.5) + 1):
        if candidate % d == 0:
            print(f'{candidate} is composite')
            break
    else:
        print(f'{candidate} is a prime number!')

    Terminal Output:

    17 is a prime number!

Part 4: Nested Loops, Patterns & Matrix Manipulation (Questions 10 to 12) 🔝

  1. Generate a right-angled triangle star pattern.
    rows = 5
    for r in range(1, rows + 1):
        print('*' * r)

    Terminal Output:

    *
    **
    ***
    ****
    *****
  2. Transpose a 2D matrix (swap rows and columns) using nested loops.
    orig = [[1, 2], [3, 4], [5, 6]]
    transposed = []
    for c in range(len(orig[0])):
        new_row = []
        for r in range(len(orig)):
            new_row.append(orig[r][c])
        transposed.append(new_row)
    print('Transposed:', transposed)

    Terminal Output:

    Transposed: [[1, 3, 5], [2, 4, 6]]
  3. Generate the first N numbers of the Fibonacci sequence.
    n_terms = 8
    fib = [0, 1]
    for _ in range(2, n_terms):
        fib.append(fib[-1] + fib[-2])
    print(f'First {n_terms} Fibonacci numbers:', fib)

    Terminal Output:

    First 8 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13]

Interactive Notebook & Practice Exercises 🔝

Work through all 12 problems interactively in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Practice interactive code cells for all 12 challenges and run self-validating assertions.

View on GitHub Run in Google Colab

Self-Verifying Unit Assertion Suite

Run these unit checks directly in Python or your local terminal to verify loop mechanics across all challenges:

# Self-verifying unit test suite for for loop mechanics
# Test 1: Natural numbers sum
total = sum(range(1, 11))
assert total == 55

# Test 2: Stepped range evens
evens = list(range(2, 21, 2))
assert len(evens) == 10 and evens[0] == 2 and evens[-1] == 20

# Test 3: Factorial
fact = 1
for x in range(1, 6):
    fact *= x
assert fact == 120

# Test 4: Matrix transpose
m = [[1, 2], [3, 4], [5, 6]]
t = [[m[r][c] for r in range(len(m))] for c in range(len(m[0]))]
assert t == [[1, 3, 5], [2, 4, 6]]

# Test 5: Fibonacci terms
fib = [0, 1]
for _ in range(2, 8):
    fib.append(fib[-1] + fib[-2])
assert fib == [0, 1, 1, 2, 3, 5, 8, 13]

print("All 12 for loop question assertions successfully verified!")

Terminal Output:

All 12 for loop question assertions successfully verified!

Frequently Asked Questions (FAQ) 🔝

When should I use for instead of while?

Use for when iterating over a known sequence or range. Use while when iteration depends on an external condition or sentinel value.

How does the for...else clause work?

The else block executes only if the loop completes all iterations without encountering a break statement.

Why is range(1, 10) stopping at 9?

The stop parameter in range() is strictly exclusive. To include 10, use range(1, 11).

How do I access both index and item in a loop?

Use the built-in enumerate() function: for idx, val in enumerate(my_list):.

Further Reading & Related Tutorials 🔝




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer