Python 中的 for 循环是什么?

Python 中的 for 循环用于迭代序列(listtuplestring)或其他可迭代对象。遍历一个序列称为遍历。

for 循环的语法

for val in sequence: loop body
这里,val是在每次迭代中获取序列内项目值的变量。
循环继续,直到我们到达序列中的最后一项。for 循环的主体使用缩进与代码的其余部分分开。

for循环流程图

image.png
Python for 循环流程图

示例:Python for 循环

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 print(“The sum is”, sum)
当你运行程序时,输出将是:
总和是 48


range() 函数

我们可以使用range()函数生成一个数字序列。range(10)将生成从 0 到 9(10 个数字)的数字。
我们还可以将开始、停止和步长定义为range(start, stop,stepsize)。如果未提供,则 stepsize 默认为 1。
该range对象在某种意义上是“懒”,因为它不会产生每一个数字,它“包含”当我们创建它。但是,它不是迭代器,因为它支持in,len和__getitem
操作。
此函数不会将所有值存储在内存中;这将是低效的。所以它会记住开始、停止、步长并在旅途中生成下一个数字。
要强制此函数输出所有项目,我们可以使用函数list()。
下面的例子将阐明这一点。

print(range(10)) print(list(range(10))) print(list(range(2, 8))) print(list(range(2, 20, 3)))
输出
范围(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
我们可以range()在for循环中使用该函数来迭代一系列数字。它可以与len()函数结合使用索引来遍历序列。这是一个例子。

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])

输出
我喜欢流行音乐 我喜欢摇滚 我喜欢爵士乐


for 循环与 else

甲for环可以有一个可选else块为好。else如果 for 循环中使用的序列中的项目耗尽,则执行该部分。
该break关键字可以用来阻止一个for循环。在这种情况下,else 部分将被忽略。
因此,如果没有中断发生,for 循环的 else 部分就会运行。
这里有一个例子来说明这一点。

digits = [0, 1, 5] for i in digits: print(i) else: print(“No items left.”)
当你运行程序时,输出将是:
0 1 5 没有物品了。
在这里,for 循环打印列表中的项目,直到循环结束。当 for 循环耗尽时,它会执行中的代码块else并打印没有物品了。
仅当未执行关键字时,此for…else语句才能与break关键字一起使用以运行else块break。让我们举个例子:

program to display student’s marks from record student_name = ‘Soyuj’ marks = {‘James’: 90, ‘Jules’: 55, ‘Arthur’: 77} for student in marks: if student == student_name: print(marks[student]) break else: print(‘No entry with that name found.’)
输出
未找到具有该名称的条目。

  1. 写一个教程:[Python while 循环](https://www.yuque.com/aifanj/odpp1n/hc9r0g)