Python provides different type of looping mechanism. while
is the most popular one after for
loops. while
loops generally used to iterate and check given condition result as boolean. If the condition is True
the loop will resume but if the condition is False
the while loop will be ended.
Python提供了不同类型的循环机制。 while
是for
循环之后最流行的一种。 while
循环通常用于迭代并检查给定条件的结果是否为布尔值。 如果条件为True
则循环将继续,但如果条件为False
,则while循环将结束。
句法 (Syntax)
Here is the syntax of while
loop in Python.
这是Python中while
循环的语法。
while (CONDITION):
STATEMENT
循环 (Loop)
In this part we will look simple but instructive example in order see how while
loop works. We will create a int variable count
and we will count up to 10
. When the counter is 10
we will stop the while loop.
在这一部分中,我们将看简单但有启发性的示例,以了解while
循环如何工作。 我们将创建一个int变量count
,最多计数10
。 当计数器为10
我们将停止while循环。
counter=0
while counter < 10:
print(counter)
counter = counter+1
无限循环(Infinite Loop)
General development problems will generally requires to stop loops if given condition is met. But some time we may need to run loops forever unless it is ended externally like killing the process. In this example we will look infinite loop
. We will put True
boolean value to the while
condition part like below.
如果满足给定条件,一般的开发问题通常需要停止循环。 但是有时我们可能需要永远运行循环,除非它像杀死进程一样在外部终止。 在这个例子中,我们将看到infinite loop
。 我们将True
布尔值放在while
条件部分,如下所示。
while (True):
print("I will run forever")
与While的其他陈述(Else Statement with While)
else
is a python statements which is used with if-elif-else
statements. But there is also use case with while
statement too. else
statement executed when while loop is ended with a False
condition. In this example we use previous example but also add else
statement and print "Previous while loop ended"
.
else
是一个与if-elif-else
语句一起使用的python语句。 但是在while
语句中也有用例。 当while循环以False
条件结束时执行else
语句。 在此示例中,我们使用前面的示例,但也添加else
语句并打印"Previous while loop ended"
。
counter=0
while counter < 10:
print(counter)
counter = counter+1
else:
print("Previous while ended loop ended")
提前终止(Premature Termination)
While running while
loops we may need to terminate the loop. There are different ways to terminate a loop. First one is we can change the condition of while
loop but this can not be easy sometimes. Second one is better, more readable and practical way. We can end the loop with break
keyword. break
will stop the loop where it issued.
在运行while
循环时,我们可能需要终止循环。 终止循环有不同的方法。 第一个是我们可以更改while
循环的条件,但是有时这并不容易。 第二种是更好,更具可读性和实用性的方法。 我们可以使用break
关键字结束循环。 break
将停止发出它的循环。
In this example we will stop the loop if the counter is equal to 5
by issuing break
keyword.
在这个例子中,如果计数器等于我们将停止循环5
通过发行break
关键字。
counter=0
while counter < 10:
if(counter==5):
break
print(counter)
counter=counter+1