Syntax of While Loop

2 min read ·

The while loop syntax defines how Python repeatedly executes a block of code based on a condition.
  • while is a keyword
  • Condition must evaluate to True or False
  • Code inside the loop must be indented

Understanding the Syntax Step by Step

  • i = 1 → initialization
  • i <= 5 → condition
  • print(i) → loop body
  • i = i + 1 → update statement

Flow of while Loop Syntax

  1. Initialize variable
  2. Check condition
  3. Execute loop body
  4. Update variable
  5. 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
  1. Write correct syntax to print numbers from 1 to 5
  2. Create a while loop using a boolean condition
  3. Identify syntax errors in a while loop
  4. Write an infinite loop using correct syntax