原文链接:https://www.programiz.com/python-programming/for-loop
Python for Loop
Table of Contents
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
表格内容
- 什么是for循环
- for循环语法
- for流程
- 例子:python for循环
- range()函数
- 带else的for循环
Syntax of for Loop
for val in sequence:
Body of for
Here, val
is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
for循环语法
>>> for val in sequence:
... Body of for
这里,val是变量,在每次迭代拿到在次序里面的每一项的值 。
循环继续直到我们获得最后一个项在次序中。对于循环的主体缩进代码与其它代码分开。
Flowchart of for Loop
for循环流程图
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
when you run the program, the output will be:
The sum is 48
例子:for循环
numbers = [6,5,3,8,4,2,5,4,11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is",sum)
当你执行程序,输出结果:
The sum is 48
The range() function
We can generate a sequence of numbers using range()
function. range(10)
will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size)
. step size defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list()
.
The following example will clarify this.
# Output: range(0, 10)
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
range()函数
我们可以使用range()函数生成一个数字序列。range(10)将生成0到9的数字(10个数字)。
我们还可以用range()定义开始,停止和步长(start,stop.step size).步长默认是1如果不提供这个参数。
在内存中这个函数的所有值没有存储,这是效率降低。因此它会记住开始,停止,步长,生产下一个运行的数字。
此函数强制输出所有项,我们可以使用函数list().
下面这个例子说明清楚。
>>> print(range(10))
range(0, 10)
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list(range(2,8)))
[2, 3, 4, 5, 6, 7]
>>> print(list(range(2,20,3)))
[2, 5, 8, 11, 14, 17]
We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len()
function to iterate though a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
When you run the program, the output will be:
I like pop
I like rock
I like jazz
我们在for()循环中使用range()函数遍历一个序列。 它与len()函数组成使用一个索引去遍历一个序列。这里有一个例子。当执行这个程序,这结果输出为:
>>> genre = ['pop','rock','jazz']
>>> for i in range(len(genre)):
... print(" I like",genre[i])
...
I like pop
I like rock
I like jazz
for loop with else
A for loop can have an optional else block as well. The else
part is executed if the items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0
1
5
No items left.
带else的for循环
一个for循环也可以有else块操作。这个else部分被执行如果使用for的每一项的序列耗尽。
break语句用于停止循环。像这样的情况,这个else部分被忽略。
因此,一个for循环的else部分被执行,如果没有break发生。
这有一个有个例子说明。
>>> digits = [0,1,5]
>>> for i in digits:
... print(i)
... else:
... print("NO items left.")
...
0
1
5
NO items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else
and prints
No items left.
这里,for循环打印列表每一项直到循环耗尽。当for循环耗尽,在else的代码块执行并打印。
Check out these examples to learn more:
- PREVIOUS
PYTHON IF...ELIF...ELSE AND NESTED IF - NEXT
PYTHON WHILE LOOP