Python While Loops

Repeat while a condition is true.

✍️ 3 exercises + code challenge in this lesson

A while loop runs as long as its condition is True.

  • break: stop the loop immediately.
  • continue: skip to the next iteration.
  • else: runs once when the condition becomes false (not after a break).
Remember to change the variable in the condition, or the loop will run forever.

Key Takeaways: Python While Loops

Mastering Python While Loops helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python While Loops Code Example

Python
balance = 1000
month = 0
while balance < 2000:
    balance *= 1.10
    month += 1
print(f"Balance doubles after {month} months: Rs {balance:.0f}")

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    if n > 7:
        break
    print("odd:", n)
Free sign-in required · Google login available

Python While Loops Practice Exercises

Check what you learned in “Python While Loops”.

/ 3 solved
Fill in the blank

Stop the loop immediately.

while True:
    
✓ Correct! Not quite. Try again.
Multiple choice

When does a while loop stop?

✓ Correct! Not quite. Try again.
Code challenge

Use a while loop to print 3, 2, 1 on separate lines.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services