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
- Initialization: Before entering the loop, any variables used in the condition must be initialized.
- Condition: The condition is a boolean expression that controls whether the loop continues or stops. It is evaluated before each iteration.
- Execution: The statements inside the loop are executed repeatedly as long as the condition remains true.
- 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 variablenum
to 1.- The while loop
while num <= 5:
checks ifnum
is less than or equal to 5. - Inside the loop:
print(num)
prints the current value ofnum
.num += 1
incrementsnum
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 untilnum
becomes 6, at which pointnum <= 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.