Nearby lessons
42 of 159Python - While Loop
- Define the while loop and when it is used
- Explain the flow of a while loop that checks the condition before each iteration
- Write while loops to print numbers, even numbers, odd numbers and reverse counting
- Identify why an infinite loop occurs when the loop variable is not updated
- Apply the while loop when the number of iterations is not known
What is a while Loop?
The while loop executes a group of statements as long as the given condition is True.
When the condition becomes False, the loop stops.
Syntax of while Loop
Flow of while Loop
- Check the condition.
- If the condition is
True, execute the loop body. - Again check the condition.
- Repeat until the condition becomes
False. - When the condition becomes
False, control comes outside the loop.
Example 1 - Print "Hello" 10 Times
Explanation
The variable i starts from 1.
After every iteration, its value increases by 1.
The loop stops when i becomes greater than 10.
Example 2 - Print Numbers from 1 to 10
Example 3 - Print Numbers from 1 to 20
Example 4 - Print Even Numbers from 1 to 20
Explanation
The loop starts from 2.
Each time, the value increases by 2, so only even numbers are printed.
Example 5 - Print Odd Numbers from 1 to 20
Explanation
The loop starts from 1.
Each time, the value increases by 2, so only odd numbers are printed.
Example 6 - Print Numbers from 10 to 1
Explanation
The loop starts from 10.
After every iteration, the value decreases by 1.
The loop stops when the value becomes less than 1.
Infinite while Loop
If the condition is always True, the loop runs forever.
Such a loop is called an Infinite Loop.
Example - Infinite while Loop
Why Does an Infinite Loop Occur?
An infinite loop happens when the loop condition never becomes False.
This usually happens when the loop variable is not updated correctly.
- The while loop executes statements as long as the condition stays True
- When the condition becomes False, the loop stops
- The condition is checked before each iteration
- An infinite loop occurs when the loop condition never becomes False
- The while loop is useful when the number of iterations is not known