Practice: Introduction to Loops

« Read the chapter

Q1. Print five lines

BeginnerCoding

Write a loop that prints the word Hi on five separate lines.

Goal: Use a simple for loop.

Q2. Sum of a list

BeginnerCoding

Use a loop to add the numbers in [3, 6, 9, 12] and print the total.

Goal: Use an accumulator.

Q3. Countdown

BeginnerCoding

Print 3, 2, 1 and then Go! using a while loop.

Goal: Write a while loop with an update.

Q4. Count vowels

IntermediateCoding

Count how many vowels are in the word 'education' and print the number.

Goal: Loop over a string with a condition.

Q5. First even number

IntermediateCoding

Find and print the first even number in [7, 9, 12, 15, 18] and stop looping.

Goal: Use break.

Q6. Skip negatives

IntermediateCoding

Print only the non-negative numbers from [4, -1, 7, -5, 0].

Goal: Use continue.

Q7. Simple trace

BeginnerOutput

What does this print?

Code
for i in range(3):
    print(i * 2)

Goal: Trace a for loop.

Q8. Loop and last value

BeginnerOutput

What does this print?

Code
for ch in 'abc':
    pass
print(ch)

Goal: Know the loop variable survives.

Q9. While countdown

BeginnerOutput

What does this print?

Code
n = 5
while n > 2:
    n -= 1
print(n)

Goal: Trace a while loop.

Q10. Else on a loop

IntermediateOutput

What does this print?

Code
for n in [1, 2, 3]:
    if n == 5:
        break
else:
    print('no break')

Goal: Understand loop else.

Q11. Accumulating strings

IntermediateOutput

What does this print?

Code
s = ''
for n in range(1, 5):
    s += str(n)
print(s)

Goal: Build a string in a loop.

Q12. Continue effect

IntermediateOutput

What does this print?

Code
total = 0
for n in range(1, 6):
    if n % 2 == 0:
        continue
    total += n
print(total)

Goal: Trace continue.

Q13. Fix the infinite loop

BeginnerDebugging

This code never ends. Fix it so it prints 1 2 3 on separate lines.

Code
n = 1
while n <= 3:
    print(n)

Goal: Fix an infinite loop.

Q14. Fix the indentation

BeginnerDebugging

Fix the code so the total is printed only once, after the loop.

Code
total = 0
for n in [1, 2, 3]:
    total += n
    print(total)

Goal: Fix indentation errors.

Q15. Choose the loop

IntermediateConceptual

Explain in one or two sentences which loop you would use to read passwords until the user types the right one, and why.

Goal: Choose between for and while.

Q16. Why use loops

BeginnerConceptual

Give two benefits of using a loop instead of copying lines.

Goal: Explain the purpose of loops.

Q17. Average of marks

IntermediateApplication

Given marks = [70, 80, 90, 60], use a loop to find the sum and print the average.

Goal: Apply an accumulator.