循环语句在绝大多数的语言中,都是必不可少的一种控制语句,循环语句允许我们执行一个语句或语句组多次。在python中有for循环和while循环两种,讲到这里,就不得不提到我们的迭代器对象

迭代器

迭代其实就是遍历,有一个接一个的意思(one by one)

迭代器对象(iterator)是python中的一个名词,有的迭代器可以重复迭代,有的迭代器只能迭代一次;迭代器可以用于for循环取出其中的子元素;迭代器对象包含有next和iter方法的实现,在正确范围内返回期待的数据以及超出范围后能够抛出StopIteration的错误停止迭代;可迭代对象(迭代工具)是包含于迭代器对象的一个概念,它包含有iter方法的实现;

 

我们可以使用isinstance()来判断一个对象是否为可迭代对象

 1 from collections import Iterable
 2 def testFunc():
 3     return 0;
 4 print(isinstance('Python', Iterable))
 5 print(isinstance([], Iterable))
 6 print(isinstance({}, Iterable))
 7 print(isinstance((1,), Iterable))  #  tuple也可以作为迭代器
 8 print(isinstance(10, Iterable))
 9 print(isinstance(True, Iterable))
10 print(isinstance(testFunc, Iterable))  #  函数不可以作为迭代器

输出:

>>> True

>>> True

>>> True

>>> True

>>> False

>>> False

>>> False

 

Python的for循环本质上就是通过不断调用next函数实现的,要注意的是,python中迭代器的规则发生了一些变化,迭代器对象应该要实现的函数是__next__()而不是next();在next中可以定义对每个元素操作并有返回值作为相应位置的值,当没有数据了,StopIteration可以用于保持当前的状态。

而对于迭代器对象,__iter__()也是必须实现的方法,它用于返回迭代器对象本身,目的是为了允许容器和迭代器被用于for和in语句中。

 

我们接下来对一个数组[1,2,3,4,5]进行迭代,使其各元素乘2并输出

# 迭代器

 1 class get_double_iter:
 2     def __init__(self):
 3         self.list = [1,2,3,4,5]
 4         self.n = 0
 5     def __next__(self):
 6         if self.n == len(self.list):
 7             raise StopIteration()
 8         else:
 9             item = self.list[self.n] * 2
10             self.n += 1
11         return item
12 # 迭代工具
13 class Fib:
14     def __init__(self):
15         pass
16     def __iter__(self):
17         return get_double_iter()
18 for f in Fib():  #  下面会介绍for循环
19 print(f)

输出:

>>> 2

>>> 4

>>> 6

>>> 8

>>> 10

 

不是只有for循环能用到迭代器,list()与tuple()方法也能用到,分别用于将迭代器转化为数组与元素。

1 arr = [1,2,3,4,5]
2 def change(x) :
3     return x + 2
4 print(list((map(change, arr))))
5 print(tuple((map(change, arr))))

输出:

>>> [3, 4, 5, 6, 7]

>>> (3, 4, 5, 6, 7)

 

for循环

for循环的基本语句是

for item in sequence:

statements(s)

sequence是一个有序列的项目,如迭代器(如map、zip迭代器)、迭代工具(如range迭代工具)或数组,或者干脆是一个字符串(这些数据类型以后会有详细讲解)

item是从sequence中遍历出的其中一个元素,它在for循环的语句块中能够被使用

statements(s)是for循环的循环主题,每一次的循环都要执行这个语句块,这个语句块可以使用item

注意:

1、如果sequence不可迭代,程序将会报错 –> 'int' object is not iterable

2、item、sequence不要求一定要这个命名。

 

rangefor循环:

range是一个迭代器,接受三个参数(起始点、结束点、步长),只有一个参数时默认由0开始,步长为1,迭代到该数的上一位;只有两个参数时默认由第一个参数开始迭代,步长为1,迭代到第二个参数的上一位。这里的记法是”左闭右开”,python中很多的规则都是左闭右开,大家深入后应该会对这句话有更深刻的理解。range的具体的使用会在后面的章节有具体介绍。

1 for index in range(5):
2 print('数字:', index)

输出:

>>> 数字: 0

>>> 数字: 1

>>> 数字: 2

>>> 数字: 3

>>> 数字: 4

1 for index in range(2, 10, 3):
2 print('数字:', index)

输出:

>>> 数字: 2

>>> 数字: 5

>>> 数字: 8

 

字符串for循环:

1 for char in 'python':
2    print('当前字母:',char)

输出:

>>> 当前字母: p

>>> 当前字母: y

>>> 当前字母: t

>>> 当前字母: h

>>> 当前字母: o

>>> 当前字母: n

 

数组for循环:

1 strArr = ['python', 'hello',  'world']
2 for item in strArr:
3 print('当前字母 :', item)

输出:

>>> 当前字母 : python

>>> 当前字母 : hello

>>> 当前字母 : world

 

map的for循环:

1 thingList = ["pyTHon", "HeLLo", "WoRLd"]
2 def change(x) :
3     return x.lower().title() # 全部换为小写后首字母转大写
4 for item in (map(change, thingList)): # map方法返回的是一个迭代器
5 print(item)

输出:

>>> Python

>>> Hello

>>> World

 

zip的for循环

1 a = [1, 2, 3, 4]
2 b = [10, 20, 30, 40, 50]
3 c = [100, 200, 300, 400, 500]
4 print(list(zip(a, b)))
5 print(list(zip(a)))
6 for item in zip(a, b, c): # 集体同时迭代,这是一个很好用的方法,迭代长度取决于最短的数组。zip方法返回的是一个迭代器
7 print(item[0], "-", item[1], "-", item[2])

输出:

>>> [(1, 10), (2, 20), (3, 30), (4, 40)]

>>> [(1,), (2,), (3,), (4,)]

>>> 1 - 10 – 100

>>> 2 - 20 – 200

>>> 3 - 30 – 300

>>> 4 - 40 – 400

 

while循环

while循环的基本语句是

while condition:

statements(s)

condition是一个判断条件,statements(s)是语句块,最先进入while循环语句时,先进行判断,若为True,则执行下面的语句块,执行语句块完毕之后,再次进行判断,如此循环,当判断语句判断为False时,不执行语句块,并退出循环。

while还有一种情况,即 while...else:

while condition:

statements(s)

else:

   statements(s2)

这种情况下,当while条件判断为False时,先不退出循环,执行else中的代码块吗,执行完毕之后,再退出循环。else中代码块不会在while是通过break跳出而中断的情况下生效。

 

while循环:

1 arr = [1, 2, 3, 4, 5, 10]
2 n = 0
3 while arr[n] < 10:
4 outStr = '执行了一次代码块: arr[' + str(n) + '] = ' + str(arr[n])
5 print(outStr)
6 n = n + 1
7 else:
8 print(arr[n])

输出:

>>> 执行了一次代码块: arr[0] = 1

>>> 执行了一次代码块: arr[1] = 2

>>> 执行了一次代码块: arr[2] = 3

>>> 执行了一次代码块: arr[3] = 4

>>> 执行了一次代码块: arr[4] = 5

>>> 10

当执行到n = 5时,进行了判断arr[5] < 10,为False,判断失败,执行else中的代码块,退出循环。

 

带break语句的while循环:

 1 arr = [1, 2, 3, 4, 5, 10]
 2 n = 0
 3 while arr[n] < 10:
 4 outStr = '执行了一次代码块: arr[' + str(n) + '] = ' + str(arr[n])
 5 print(outStr)
 6 n = n + 1
 7 if(arr[n] > 4):
 8     break
 9 else:
10 print(arr[n])

输出:

>>> 执行了一次代码块: arr[0] = 1

>>> 执行了一次代码块: arr[1] = 2

>>> 执行了一次代码块: arr[2] = 3

>>> 执行了一次代码块: arr[3] = 4

当执行到n = 4时,进行了语句块中的判断arr[4] > 4,为True,判断成功,执行break,由于是非正常退出,不执行else中的代码块。

Continue语句是用来结束本次循环体的语句,当执行continue时,将重新回到循环体中开始下一次的循环,当然,进入代码块前依旧需要进行判断。

 

带continue语句的while循环:

1 while True:
2 your_name = input('your name is :')
3 if your_name == 'jobs':
4     break;
5 else:
6         continue;

输出:

>>> your name is :a

>>> your name is :a

>>> your name is :jobs

这个while循环是一个死循环,因为他的判断条件时True,但是我们在语句块中定义了一些判定条件,使得它不会一直执行下去,请保证你的代码不会一直执行(除非你需要的话),必要时可以使用CTRL + C停止运行。当输入为a时,判断错误,执行continue语句,跳出本次循环进入下一次循环,所以这段代码会一直让你输入名字,知道输入的为jobs时,执行break退出循环。

 

到这里我们已经讲了python的两种循环方式了,希望大家看过之后,能对大家的python有一点帮助,谢谢!