Python - While Loops
Code Life
By Pierre Marsaa
Introduction to While Loops
A while loop allows you to repeat a block of code as long as a condition is True. Unlike for loops which iterate over a sequence, while loops continue until a condition becomes False.
The basic syntax is:
Loading editor...
Here's a simple example of a while loop that counts from 1 to 5:
↗️
Loading editor...
↶
↷
Notice three important parts:
1.
We initialize a variable before the loop
2.
We use this variable in the condition
3.
We update the variable inside the loop. This way, when the condition becomes False, the loop stops.
Verify