Creating Loops with While Statements
In this lesson, you will learn how to make your programs perform a task repeatedly by using the while statement.
The Concept of Iteration
Up until now, your code has executed line-by-line, moving steadily from top to bottom. However, real-world programs often need to repeat a specific action until a certain goal is met. Think of a while loop like a set of instructions that says, "Keep doing this as long as this condition is met."
A while loop checks a condition (the same kind you used with if statements) before every repetition. If the condition is True, the code inside the loop block runs. Once the code finishes, the program jumps back to the top and checks the condition again. If the condition becomes False, the loop stops, and the program moves on to the next line of code outside the block.
Writing Your First Loop
Here is a simple example that counts down from 3:
count = 3
while count > 0:
print(count)
count = count - 1
print("Blastoff!")
In this code:
- We initialize
countat 3. - The
whileloop checks: "Iscountgreater than 0?" - Since 3 is greater than 0, it prints
3and updatescountto2. - The loop runs again, printing
2, then1. - Eventually,
countbecomes 0. The loop checks the condition again, finds it isFalse(because 0 is not greater than 0), and skips the loop.
Avoiding Infinite Loops
Because the while loop relies on a condition, you must ensure that your loop has a way to eventually become False. If your condition is always True (for example, if you forgot to decrease the count), your program will get stuck in an "infinite loop" and never finish. Always make sure your logic includes a way to change the state of your variables so the loop can exit!
Key Takeaway: A while loop allows a block of code to run repeatedly as long as a specified condition evaluates to True.