So far we have seen that Python executes code in a sequence and each block of code is executed once.
Loops allow us to execute a block of code several times.
While Loop
Allows us to execute a block of code several times as long as the condition is
True
. While Loop Example
The following code snippet prints the next three consecutive numbers after a given number.
Code
PYTHON
Input
Output
Possible Mistakes
1. Missing Initialization
Code
PYTHON
Input
Output
2. Incorrect Termination Condition
Code
PYTHON
Input
Output
The above code runs into an infinite loop.
While block will keep repeating as the value in condition variable is
True
.3. Not Updating Counter Variable
Code
PYTHON
Input
Output
As the value of counter is not updating.