Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

While Loop Exercises

While loops continue executing as long as a condition remains True. They're perfect for situations where you don't know exactly how many iterations you need.

Key Concepts

Basic While Loop

while condition:
    # code to execute
    # don't forget to update the condition!

Common Patterns

  • Countdown: while n > 0:
  • Input validation: while not valid_input:
  • Processing until condition: while more_data:
  • Search until found: while not found:

Important: Avoid Infinite Loops

Always ensure the condition will eventually become False:

# Good - counter decreases
counter = 10
while counter > 0:
    counter -= 1

# Bad - infinite loop!
while True:
    print("This runs forever")

Tips

  • Use break to exit early
  • Use continue to skip to next iteration
  • Consider if a for loop might be better
  • Always have a plan for when the loop should end