Python教程-2.2节:Python for循环

Python for循环

在本文中,您将学习使用for循环的不同变体来迭代一系列元素。

什么是Python中的for循环?

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

for循环的语法

for val in sequence:
	Body of for

在此,val是在每次迭代中获取序列内项目值的变量。

循环继续直到我们到达序列中的最后一项。使用缩进将for循环的主体与其余代码分开。

for循环流程图

Python编程中的for Loop流程图
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)
	

运行代码

当您运行程序时,输出将是:

The sum is 48

range()函数

我们可以使用range()函数生成数字序列。range(10)会产生0到9之间的数字(10个数字)。

我们还可以将开始,停止和步长定义为range(start, stop,step_size)。如果未提供,则step_size默认为1。

range某种意义上说,该对象是“惰性”的,因为它在创建对象时不会生成它“包含”的每个数字。然而,这不是一个迭代器,因为它支持inlen__getitem__操作。

此功能不会将所有值存储在内存中;这将是低效的。因此它会记住开始,停止,步长并在旅途中生成下一个数字。

要强制此函数输出所有项目,可以使用函数list()

以下示例将阐明这一点。

print(range(10))

print(list(range(10)))

print(list(range(2, 8)))

print(list(range(2, 20, 3)))

运行代码

输出量

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

运行代码

运行该程序时,输出为:

I like pop
I like rock
​I like jazz

for循环和else一同使用

for环可以有一个可选else块为好。else如果用于for循环的序列中的项目用尽,则会执行该零件。

break关键字可以用来阻止一个for循环。在这种情况下,其他部分将被忽略。

因此,如果没有中断发生,则for循环的else部分将运行。

这是一个示例来说明这一点。

digits = [0, 1, 5]

for i in digits:
    print(i)
else:
    print("No items left.")

运行代码

运行该程序时,输出为:

0
1
5
No items left.

在这里,for循环将打印列表中的项目,直到循环用尽。当for循环用尽时,它执行并在其中else打印代码块没有剩余的项目。

仅当未执行关键字时,此for...else语句可与break关键字一起使用以运行elsebreak。让我们举个例子:

# 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.')

运行代码

输出量

No entry with that name found.
0