python中的循环

In this section, we will see how loops work in python. Looping is simply a functionality that is commonly used in programming for achieving repetitive tasks. It can vary from iterating each element of an array or strings, to modifying a whole database.

在本节中,我们将看到循环如何在python中工作。 循环只是在编程中通常用于完成重复性任务的功能。 它可以从迭代数组或字符串的每个元素到修改整个数据库。

The thumb rule for using loops is:

使用循环的经验法则是:

If you're writing a similar piece of code, again and again, it's time to go for the loops.

如果您要编写类似的代码,那么就该去循环了。

Instead of doing,

而不是做

>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4

and so on, do it like,

依此类推,

>>> a = []
>>> {run a loop in this line to store 1, 2, 3, 4 in list a}

In the second code snippet, we will be using a loop, where we will only have to write whatever tedious task we have to achieve, only once, and then put it on a loop. With this, we will be able to achieve an iterative flow for execution.

在第二个代码段中,我们将使用一个循环,在该循环中,我们只需编写一次必须完成的繁琐任务即可,然后将其放入循环中。 这样,我们将能够实现执行的迭代流程。

In python, there are two ways to achieve iterative flow:

在python中,有两种方法可以实现迭代流程:

  1. Using the for loop
    使用for循环
  2. Using the while loop
    使用while循环

for循环 (The for loop)

Let us first see what's the syntax,

首先让我们看看语法是什么

for [ELEMENT] in [ITERATIVE-LIST]:
	[statement to execute]
else:
	[statement to execute when loop is over]
	[else statement is completely optional]

for loop is frequently used to iterate elements of lists. Considering the above syntax, let's say there is a list myList:

for循环通常用于迭代列表的元素。 考虑到以上语法,假设有一个列表myList

>>> myList = [8, 9, 2, 3, 4, 6]

If we want to iterate all the elements of the list myList using the for loop:

如果要使用for循环迭代列表myList所有元素:

for i in myList:
	print (i)

As we can see we are using a variable i, which represents every single element stored in the list, one by one. Our loop will run as many times, as there are elements in the lists. For example, in myList there are 6 elements, thus the above loop will run 6 times.

如我们所见,我们正在使用变量i ,该变量i代表列表中存储的每个单个元素。 我们的循环将运行许多次,就像列表中的元素一样。 例如,在myList有6个元素,因此上述循环将运行6次。

During the first iteration, the value of i will be 8, while in next it will be 9 and so on, uptill 6, in the last iteration. Doing so, one can easily use these individual list element values inside the loop, as in our case, we have printed them.

在第一次迭代期间, i的值为8 ,而在下一个迭代期间, i的值为9 ,依此类推,直到6 。 这样做,可以轻松地在循环内使用这些单独的列表元素值,就像在我们的例子中,我们已经打印了它们。

Besides this, there is another way of doing it. If you can recall, our old traditional way of accessing an element of the list by index - myList[i]. Although, in this case, we will be using another function range() (or alternatively xrange() can also be used). range() function has already been mentioned in the previous sections too. If you can remember range() function can return you a list of numbers according to the arguments that you provide. For example:

除此之外,还有另一种方法。 如果您还记得,那是我们通过index- myList[i]访问列表元素的传统方法。 尽管在这种情况下,我们将使用另一个函数range() (或者也可以使用xrange() )。 在前面的部分中也已经提到了range()函数。 如果您还记得, range()函数可以根据您提供的参数返回一个数字列表。 例如:

>>> range(5)

[0, 1, 2, 3, 4]

[0,1,2,3,4]

Or,

要么,

>>> range(5, 10)

[5, 6, 7, 8, 9]

[5,6,7,8,9]

Or,

要么,

>>> range(2, 12, 2)

[2, 4, 6, 8, 10]

[2、4、6、8、10]

We can use range() function along with the for loop to iterate index number from 0 to len(myList). It will be pretty much like:

我们可以将range()函数与for循环一起使用, for将索引号从0迭代到len(myList) 。 它将非常像:

for i in range(0, len(myList)):
	print (myList[i])

As you might have noticed, in this case, we will be iterating over a temporary list which contains the index numbers of the actual list. This temporary list is generated using range() function.

实际列表索引号的临时 列表 。 此临时列表是使用range()函数生成的。

The else block in for loop

elsefor循环

The else block with the for loop, is executed, once all the elements of the list are iterated or there are no more elements left to iterate in the list. It'll be safe to say that else statement is executed at the end of the loop. Although, as already mentioned in the syntax, it's completely optional to use and in fact, it's not even frequently used.

一旦列表的所有元素都被迭代,或者列表中没有其他元素可以迭代,则执行带有for循环的else块。 可以肯定地说else语句在循环结束时执行。 尽管,正如语法中已经提到的那样,使用它是完全可选的,实际上,它甚至不经常使用。

Looking at some more complex examples, let's say there is a list of lists:

看一些更复杂的示例,假设有一个列表列表:

>>> bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]

How do you think, we will be accessing each element of the list?

您如何看待,我们将访问列表的每个元素?

The answer is, using a loop within another loop. Since there are lists within a list, thus the outer loop will help in accessing each list of the bigList, and inside that loop, for every list element we will be using another loop.

答案是,在另一个循环中使用一个循环。 由于列表中存在列表,因此外循环将有助于访问bigList每个列表,在该循环内部,对于每个列表元素,我们将使用另一个循环。

for i in bigList:
	for j in i:
		print ("Element of list within a list - ", j)

Element of list within a list - 1 Element of list within a list - 3 Element of list within a list - 6 Element of list within a list - 8 Element of list within a list - 2 Element of list within a list - 0 Element of list within a list - 4 Element of list within a list - 7 Element of list within a list - 10 Element of list within a list - 1 Element of list within a list - 5 Element of list within a list - 2 Element of list within a list - 6

列表中的列表元素-1列表中的列表元素-3列表中的列表元素-6列表中的列表元素-8列表中的列表元素-2列表中的列表元素-0元素列表内的列表-4列表内的列表元素-7列表内的列表元素-10列表内的列表元素-1列表内的列表元素-5列表内的列表元素-2列表内的元素清单-6

while循环 (The while loop)

It's time to learn about the while loop.

现在是时候学习while循环了。

Syntax:

句法:

while [condition]:
	[statement to execute]
else:
	[statement to execute if condition is false]
	[else statement is completely optional]

Again, in the while loop too, there is an else block, although it's optional and rarely used.

同样,在while循环中,还有一个else块,尽管它是可选的,很少使用。

In the first statement, while loop sets a condition, then a statement, and the compiler following the flow of execution, first checks the condition provided in the condition block, if the condition holds True, then the statement is executed.

在第一个语句中, while循环设置一个condition ,然后一个语句 ,然后编译器按照执行流程,首先检查条件块中提供的条件,如果条件保持True ,则执行该语句。

Once the statement is executed, the compiler checks the condition again, if it's True again then the statement is again executed, otherwise the else block is executed (if provided) or simply the flow control breaks out of the while loop (if else statement is not mentioned).

一旦执行了该语句,编译器将再次检查条件,如果再次为True ,则再次执行该语句,否则将执行else块(如果提供),或者只是流程控制会退出while循环(如果else语句为未提及)。

Here is an example:

这是一个例子:

Caution:

警告:请勿在IDE或IDLE或任何地方尝试此示例。

while True:
	print ("I am printing because the condition is True")

Since here we have set our condition to be True, hence the compiler will execute the statement the first time. In next iteration, the condition will still be True again and thus the statement will be executed again. This will keep on happening and as you might have guessed there will be no end for this loop. Such kind of looping is called infinite loop

由于这里我们将条件设置为True ,因此编译器将在第一次执行该语句。 在下一次迭代中,条件仍将再次为True ,因此该语句将再次执行。 这将继续发生,并且您可能已经猜到此循环没有尽头。 这种循环称为无限循环

Time for another example:

时间再举一个例子:

i = 0
while i < 5:
	i=i+1
	print ("i =", i)

In this case, in the first iteration condition i < 5 is checked, since 0 < 5, hence the statement is executed. During execution, value of i is incremented by 1.

在这种情况下,在第一次迭代条件下检查i < 5 ,因为0 < 5 ,所以执行了该语句。 在执行期间, i值增加1

The for loop, is frequently used for iterating elements of a list, while loop on the other hand, is capable of serving several purposes, and it can iterate a list too! The logic is pretty much similar for accessing an element using indices. Run the loop from 0 to len(myList) and simply access the elements. And, there will be no need of using range() or xrange() function.

for循环通常用于迭代列表中的元素, while循环则可以用于多种目的,并且也可以迭代列表! 使用索引访问元素的逻辑非常相似。 运行从0len(myList)的循环,只需访问元素。 并且,将不需要使用range()xrange()函数。

myList = [8, 9, 2, 3, 4, 6]
i = 0
while i < len(myList):
    print (myList[i])
    i = i+1;

Quickly going through the example for lists within a list:

快速浏览示例列表中的列表:

bigList = [[1, 3, 6], [8, 2,], [0, 4, 7, 10], [1, 5, 2], [6]]
i = 0
j = 0
while i<len(bigList):
	while j<len(bigList[i]):
		print (“Element of list within a list -”,bigList[i][j])
		j=j+1;
	i=i+1

continue关键字 (The continue keyword)

continue keyword is used inside the loops for altering the loop execution. Using continue inside the loop will skip the current statement execution, and it will check the condition again. Suppose there is a string,

在循环内部使用continue关键字来更改循环执行。 在循环内部使用continue将跳过当前语句的执行,并将再次检查条件。 假设有一个字符串,

>>> name = "StudyTonight"

So let's have a quick example demonstrating use of continue keyword:

因此,让我们看一个简单的示例,演示使用continue关键字:

for i in name:
	continue
	print (i)

It will print nothing. Let's see why? In the first iteration, first element of the list name will be picked, i.e. "S", the next statement inside the for loop is continue, thus as soon as this keyword is found, the execution of rest of the for loop statements is skipped and the flow gets back to the for loop starting to get the next element and check the condition. Same steps are followed by the next element of our string, i.e., "t" and the continue interrupts the flow again, and this will happen everytime the execution flow reaches the continue keyqord.

它不会打印任何内容 。 让我们看看为什么? 在第一次迭代中,将选择列表name第一个元素,即"S"for循环内的下一条语句为continue ,因此,一旦找到此关键字,就会跳过其余的for循环语句的执行。然后流程返回到for循环,开始获取下一个元素并检查条件。 字符串的下一个元素(即"t"之后执行相同的步骤, continue再次中断该流,并且每次执行流到达continue keyqord时都会发生这种情况。

So, now if we want to write a program with a loop which prints only the lowercase letters of the string stored in the name variable, then, we can use the continue keyword to skip those letters which are not lowercase.

因此,现在,如果我们要编写一个带有循环的程序,该循环仅打印存储在name变量中的字符串的小写字母,那么,我们可以使用continue关键字跳过那些不是小写字母的字母。

for i in name:
	if not i.islower():
		continue
	print (i)

if condition checks whether the element i is in lowercase, using islower() function. If it is not in lowercase then the rest of the statements are simply skipped and the print statement is never executed, although, if i is in lowercase then the if statement returns False and continue statement is not executed.

if condition使用islower()函数检查元素i是否为小写。 如果不是小写字母,则仅跳过其余语句,并且永远不会执行print语句,尽管如果i是小写字母,则if语句返回Falsecontinue语句不会执行。

The continue keyword works in the exact same way for the while loop as well.

对于while循环, continue关键字的工作方式也完全相同。

break关键字 (The break keyword)

break keyword is used inside the loop to break out of the loop. Suppose while iterating over the characters of the string stored in the variable name, you want to break out of it as soon as the character "T" is encountered. This is how it can be done:

break关键字在循环内部使用,以脱离循环。 假设在迭代存储在变量name中的字符串的字符时,您想在遇到字符"T"立即退出。 这是可以做到的:

for i in name:
	if i == "T":
		break;
	print (i)

Now, as soon as the if condition gets the character "T", the compiler will execute the break statement and flow of execution will get out of the loop.

现在,只要if条件获得字符"T" ,编译器将执行break语句,执行流程将退出循环。

翻译自: https://www.studytonight.com/python/looping-in-python

python中的循环