Syntax of While Loop
2 min read ·
The
while loop syntax defines how Python repeatedly executes a block of code based on a condition.whileis a keyword- Condition must evaluate to
TrueorFalse - Code inside the loop must be indented
Understanding the Syntax Step by Step
i = 1→ initializationi <= 5→ conditionprint(i)→ loop bodyi = i + 1→ update statement
Flow of while Loop Syntax
- Initialize variable
- Check condition
- Execute loop body
- Update variable
- Repeat until condition becomes False
Condition in while Loop
The condition can be:
- Comparison expression
- Boolean variable
- Logical expression
Example with Comparison
while Loop with Boolean Condition
while Loop with Logical Operators
while Loop with User Input Syntax
Empty while Loop (Using pass)
Note
pass is used when syntax is required but logic is not written yet.
Incorrect Syntax Examples
Missing Colon ❌
Missing Indentation ❌
Stop
Colon and indentation are mandatory in while loop syntax.
Infinite Loop Syntax
Caution
Use infinite loops carefully and always provide an exit condition.
Real World Example
Real World Scenario
Menu-driven program keeps running until exit condition
Exercise
Practice Task
- Write correct syntax to print numbers from 1 to 5
- Create a
whileloop using a boolean condition - Identify syntax errors in a
whileloop - Write an infinite loop using correct syntax