Python while loop


A while loop in Python is used to repeatedly execute a block of statements as long as a condition is true. It is a type of indefinite loop where the number of iterations is not specified explicitly but rather determined by the condition.

Syntax 

while condition:
    # Execute these statements
    # Continue looping as long as condition is true

Properties of a while loop

  1. Initialization: Before entering the loop, any variables used in the condition must be initialized.
  2. Condition: The condition is a boolean expression that controls whether the loop continues or stops. It is evaluated before each iteration.
  3. Execution: The statements inside the loop are executed repeatedly as long as the condition remains true.
  4. Termination: The loop terminates when the condition becomes false. If the condition is initially false, the statements inside the loop will not execute at all.

Example:

Let's look at a simple example to illustrate the while loop in action. Suppose we want to print numbers from 1 to 5 using a while loop.

# Example of a while loop
num = 1
while num <= 5:
    print(num)
    num += 1

Here

  • num = 1 initializes the variable num to 1.
  • The while loop while num <= 5: checks if num is less than or equal to 5.
  • Inside the loop:
    • print(num) prints the current value of num.
    • num += 1 increments num by 1 after each iteration.
  • The loop continues to run and print numbers from 1 to 5 (inclusive) because each time num is printed and incremented until num becomes 6, at which point num <= 5 evaluates to false, and the loop terminates.

Important Points

Infinite Loops: Be cautious to ensure the loop condition eventually becomes false; otherwise, it leads to an infinite loop.
Initial Condition: Ensure the initial condition is true at least once to execute the loop.
Modifying Condition: Inside the loop, ensure the condition can eventually become false to exit the loop.

While loops are useful when the number of iterations is not known beforehand and depends on some condition that may change during the execution of the loop.