Menu Close

Python for 循环语句及范例

在本文中,您将学习使用for循环的不同变体对元素序列进行迭代。

1. 什么是 Python 中的for循环?

Python 中的 for 循环用于迭代序列(列表、元组、字符串)或其他可迭代对象。在序列上进行迭代称为遍历。

1) for循环的语法

for val in sequence:
      Body of for

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

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

2) for循环流程图

Python 中for循环的流程图
Python 中for循环的流程图

例1.1  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

3)range()函数

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

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

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

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

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

以下示例将阐明这一点。

例1.2 range()函数的应用

print(range(10))

print(list(range(10)))

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

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

结果

我们可以在for循环中使用range()函数来迭代数字序列。 它可以与len()函数结合使用索引来遍历序列。 这是一个例子。

例1.3 range()函数对字符串的应用

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

结果

4.循环与else

for循环也可以具有可选的else块。 如果for循环的序列中的项目用尽,则会执行else部分。

break关键字可用于停止for循环。 在这种情况下,其他部分将被忽略。

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

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

例1.4 打印序列中的数字

digits = [0, 1, 5]

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

结果

0
1
5
No items left.

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

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

例1.5 检查学生分数

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

2. 举例分析python for 循环

例2.1 – for 循环和

#
#Example file for working with loops
#
x=0
#define a while loop
#	while(x <4):
#		print x
#		x = x+1

#Define a for loop 
for x in range(2,7):
		print(x)

结果


例2.2 while循环打印出2.1同样结果

#
#Example file for working with loops
#
x=2
#define a while loop
while(x <7):
		print(x)
		x = x+1

结果

例2.3 for循环在字符串的应用

#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for m in Months:
		print(m)

例2.4 for循环中利用break

# use the break and continue statements
for x in range (10,20):
    if (x == 15): break
    print(x)

结果

10
11
12
13
14

例2.4 for循环中利用continue

for x in range (10,20):
	if (x % 5 == 0) : continue
	print(x)

结果

11
12
13
14
16
17
18
19

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Leave the field below empty!

Posted in Python教程

Related Posts