📅  最后修改于: 2020-10-24 08:55:37             🧑  作者: Mango
默认情况下,以任何编程语言编写的程序流都是顺序的。有时我们可能需要更改程序的流程。特定代码的执行可能需要重复几次。
为此,编程语言提供了各种类型的循环,这些循环能够多次重复某些特定的代码。考虑下图以了解循环语句的工作。
循环将复杂的问题简化为简单的问题。它使我们能够更改程序的流程,从而不必一次又一次地编写相同的代码,而可以将相同的代码重复有限的次数。例如,如果我们需要print的第10张自然数的话,而不是用print语句的10倍,我们可以它运行多达10次迭代循环内print。
Python中循环具有以下优点。
Python有以下循环语句。
Loop Statement | Description |
---|---|
for loop | The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. |
while loop | The while loop is to be used in the scenario where we don’t know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop. |
do-while loop | The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs). |