Practice: Introduction to Loops
Q1. Print five lines
Write a loop that prints the word Hi on five separate lines.
Goal: Use a simple for loop.
Q2. Sum of a list
Use a loop to add the numbers in [3, 6, 9, 12] and print the total.
Goal: Use an accumulator.
Q3. Countdown
Print 3, 2, 1 and then Go! using a while loop.
Goal: Write a while loop with an update.
Q4. Count vowels
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
Find and print the first even number in [7, 9, 12, 15, 18] and stop looping.
Goal: Use break.
Q6. Skip negatives
Print only the non-negative numbers from [4, -1, 7, -5, 0].
Goal: Use continue.
Q7. Simple trace
What does this print?
for i in range(3):
print(i * 2)Goal: Trace a for loop.
Q8. Loop and last value
What does this print?
for ch in 'abc':
pass
print(ch)Goal: Know the loop variable survives.
Q9. While countdown
What does this print?
n = 5
while n > 2:
n -= 1
print(n)Goal: Trace a while loop.
Q10. Else on a loop
What does this print?
for n in [1, 2, 3]:
if n == 5:
break
else:
print('no break')Goal: Understand loop else.
Q11. Accumulating strings
What does this print?
s = ''
for n in range(1, 5):
s += str(n)
print(s)Goal: Build a string in a loop.
Q12. Continue effect
What does this print?
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
This code never ends. Fix it so it prints 1 2 3 on separate lines.
n = 1
while n <= 3:
print(n)Goal: Fix an infinite loop.
Q14. Fix the indentation
Fix the code so the total is printed only once, after the loop.
total = 0
for n in [1, 2, 3]:
total += n
print(total)Goal: Fix indentation errors.
Q15. Choose the loop
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
Give two benefits of using a loop instead of copying lines.
Goal: Explain the purpose of loops.
Q17. Average of marks
Given marks = [70, 80, 90, 60], use a loop to find the sum and print the average.
Goal: Apply an accumulator.