Loops — Exercises

Practice for-loops, while-loops, enumerate, break/continue and loop patterns.

1. For loop basics

  1. Print numbers from 1 to 20 using for and range.
  2. Use enumerate to print index + item for list ['a','b','c'].

2. While loops

  1. Write a while loop that counts down from 10 to 1 and prints "Lift off!" after the loop.
  2. Implement a password prompt that allows up to 3 attempts using a while loop. Stop on success.

3. Advanced patterns

  1. Compute Fibonacci numbers up to n using a loop and store them in a list.
  2. Given a list, remove all even numbers in-place without creating a new list (be careful while iterating).

4. Output prediction

  1. Predict output:
    for i in range(3):
        for j in range(2):
            print(i, j)
  2. Predict output:
    i = 0
    while i < 3:
        i += 1
        if i == 2:
            continue
        print(i)

← Back to Topics


Show answers — Loops worksheet

1. For loop basics

# 1. 1 to 20
for i in range(1, 21):
    print(i)

# 2. enumerate example
for idx, ch in enumerate(['a','b','c'], start=1):
    print(idx, ch)

2. While loops

# 3. countdown
i = 10
while i > 0:
    print(i)
    i -= 1
print("Lift off!")

# 4. password attempts
password = "secret"
attempts = 0
while attempts < 3:
    guess = input("Guess: ")
    if guess == password:
        print("Welcome")
        break
    attempts += 1
else:
    print("No more attempts")

3. Advanced patterns

# 5. Fibonacci
n = 10
a, b = 0, 1
fib = []
while len(fib) < n:
    fib.append(b)
    a, b = b, a + b
print(fib)

# 6. remove even numbers in-place safely
nums = [1,2,3,4,5,6]
i = 0
while i < len(nums):
    if nums[i] % 2 == 0:
        nums.pop(i)
    else:
        i += 1
print(nums)  # [1,3,5]

4. Output prediction

# 7. nested loops output:
# 0 0
# 0 1
# 1 0
# 1 1
# 2 0
# 2 1

# 8. while prediction:
# prints 1 then 3
i = 0
while i < 3:
    i += 1
    if i == 2:
        continue
    print(i)  # prints 1 then 3