Practice: while Loop
Q1. Print 1 to 5
Use a while loop to print the numbers 1 to 5.
Goal: Write a basic while loop.
Q2. Even numbers
Print the even numbers from 2 to 10 using a while loop.
Goal: Change the step.
Q3. Sum to 100
Use a while loop to add the numbers 1 to 100 and print the total.
Goal: Use a counter and accumulator.
Q4. Digit count
Count the digits of 98765 using a while loop and integer division, then print the count.
Goal: Use while with unknown repeats.
Q5. Double until big
Start with 1 and double it until it passes 100. Print the final value.
Goal: Use a condition on a changing value.
Q6. Sentinel sum
Simulate reading numbers 4, 6, 10 and then 0 as a stop signal from a list, adding all before 0. Print the total.
Goal: Use a sentinel value.
Q7. Countdown output
What does this print?
n = 3
while n > 0:
print(n, end=' ')
n -= 1Goal: Trace a countdown.
Q8. Value after loop
What does this print?
n = 0
while n < 4:
n += 1
print(n)Goal: Know the value after the loop.
Q9. Zero iterations
What does this print?
n = 10
while n < 5:
print('in loop')
n += 1
print('out')Goal: Understand zero iterations.
Q10. While else
What does this print?
n = 0
while n < 3:
n += 1
else:
print('else', n)Goal: Understand while else.
Q11. Break position
What does this print?
n = 0
while True:
n += 3
if n > 10:
break
print(n)Goal: Trace while True.
Q12. Collatz steps
What does this print?
n = 6
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
print(steps)Goal: Trace a longer while loop.
Q13. Fix the infinite loop
This loop never ends. Fix it so it prints 0, 1, 2.
i = 0
while i < 3:
print(i)Goal: Fix an infinite loop.
Q14. Fix the continue trap
This loop gets stuck. Fix it so it prints 1 3 5 on one line separated by spaces.
n = 0
while n < 6:
if n % 2 == 0:
continue
n += 1
print(n, end=' ')Goal: Place updates before continue.
Q15. Why while True is safe
Explain when while True is safe to use.
Goal: Explain while True.
Q16. For or while
Which loop would you choose to print every item in a list, and why?
Goal: Choose the right loop.
Q17. Savings goal
You save 500 each month and want to reach 3000. Use a while loop to count the months needed and print it.
Goal: Apply a while loop to a real problem.