A while loop in Python repeatedly executes a block of code as long as a specified condition is True. Here's a simple guide on how to use while loops:
Basic Structure
while condition:
# Code to execute
Example
Here's a basic example that counts from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1 # Increment count by 1
Explanation
- Initialization:
countis set to 1. - Condition: The loop continues as long as
countis less than or equal to 5. - Execution: Inside the loop, it prints the current value of
count. - Increment:
countis increased by 1 in each iteration.
Important Notes
- Infinite Loops: Ensure the condition will eventually become
False, or you'll create an infinite loop. - Breaking the Loop: You can use the
breakstatement to exit the loop prematurely if needed.
Summary
while loops are useful for situations where the number of iterations isn't known beforehand. For more practice with loops, consider exploring related labs on LabEx!
