Practice: while Loop

« Read the chapter

Q1. Print 1 to 5

BeginnerCoding

Use a while loop to print the numbers 1 to 5.

Goal: Write a basic while loop.

Q2. Even numbers

BeginnerCoding

Print the even numbers from 2 to 10 using a while loop.

Goal: Change the step.

Q3. Sum to 100

IntermediateCoding

Use a while loop to add the numbers 1 to 100 and print the total.

Goal: Use a counter and accumulator.

Q4. Digit count

IntermediateCoding

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

IntermediateCoding

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

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
n = 3
while n > 0:
    print(n, end=' ')
    n -= 1

Goal: Trace a countdown.

Q8. Value after loop

BeginnerOutput

What does this print?

Code
n = 0
while n < 4:
    n += 1
print(n)

Goal: Know the value after the loop.

Q9. Zero iterations

BeginnerOutput

What does this print?

Code
n = 10
while n < 5:
    print('in loop')
    n += 1
print('out')

Goal: Understand zero iterations.

Q10. While else

IntermediateOutput

What does this print?

Code
n = 0
while n < 3:
    n += 1
else:
    print('else', n)

Goal: Understand while else.

Q11. Break position

IntermediateOutput

What does this print?

Code
n = 0
while True:
    n += 3
    if n > 10:
        break
print(n)

Goal: Trace while True.

Q12. Collatz steps

AdvancedOutput

What does this print?

Code
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

BeginnerDebugging

This loop never ends. Fix it so it prints 0, 1, 2.

Code
i = 0
while i < 3:
    print(i)

Goal: Fix an infinite loop.

Q14. Fix the continue trap

AdvancedDebugging

This loop gets stuck. Fix it so it prints 1 3 5 on one line separated by spaces.

Code
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

IntermediateConceptual

Explain when while True is safe to use.

Goal: Explain while True.

Q16. For or while

BeginnerConceptual

Which loop would you choose to print every item in a list, and why?

Goal: Choose the right loop.

Q17. Savings goal

IntermediateApplication

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.