The While Loop
You'll learn how to use a while loop to repeat code automatically as long as a condition stays true.
What Is a While Loop?
A while loop is a control structure that repeats a block of code over and over, but only as long as a specified condition remains true. Think of it like a guard at a door: "While you have a ticket, you can keep entering." Once the condition becomes false, the loop stops and your program moves on.
How It Works
The while loop checks a boolean condition before each repetition. If the condition is true, the code inside the loop runs. After that code executes, the loop checks the condition again. This cycle continues until the condition evaluates to false.
Basic syntax:
while condition:
# code to repeat
A Simple Example
count = 1
while count <= 3:
print(count)
count = count + 1
What happens:
- First check: Is
count <= 3? Yes (1 ≤ 3), so print 1, then increment to 2 - Second check: Is
count <= 3? Yes (2 ≤ 3), so print 2, then increment to 3 - Third check: Is
count <= 3? Yes (3 ≤ 3), so print 3, then increment to 4 - Fourth check: Is
count <= 3? No (4 > 3), so stop
The output is: 1, 2, 3
Why It Matters
While loops let you automate repetitive tasks without writing the same code multiple times. They're essential when you don't know in advance how many times something needs to repeat—you just know when to stop.
Key Takeaway: A while loop repeats code as long as its condition is true, checking the condition before each iteration.