What is the usage of while loop in Python programming?
While is a loop structure in Python that is used to repeatedly execute a block of code until a specified condition is no longer met.
The syntax format of “while” is as follows:
while 条件:
# 执行的代码块
When performing a loop, the condition is first checked to see if it is true. If the condition is true, the code block is executed. After executing the code block, the condition is checked again. If the condition is still true, the code block continues to be executed. The loop stops when the condition is no longer true.
Here is a simple example of a while loop that will print numbers 1 to 5:
i = 1
while i <= 5:
print(i)
i += 1
Output result:
1
2
3
4
5
In the given example, the variable i starts with a value of 1. The while loop will continue to run until the value of i is greater than 5. In each loop, the current value of i is printed out and the value of i is incremented by 1. When the value of i reaches 6, the condition i <= 5 is no longer met, and the loop stops.
It is important to note that if the condition is not initially met, the code inside the loop will not be executed, as shown below:
i = 10
while i <= 5:
print(i)
i += 1
Because the initial condition i is greater than 5, the code inside the loop will not execute, and the loop will end immediately without printing anything.
When using a while loop, it is important to avoid the occurrence of an infinite loop, where the condition always remains true and the loop cannot stop. To prevent an infinite loop, it is common to add code within the loop that can change the condition, ultimately making it false and ending the loop.