循环
循环的作用在于将一段代码重复执行多次。
while 循环
while <condition>:
<statesments>
Python会循环执行<statesments>
,直到<condition>
不满足为止。
例如,计算数字1
到10
的和:
i = 1
total = 1
while i < 10:
total += i
i += 1
print(total)
55
之前提到,空容器会被当成 False
,因此可以用 while
循环来读取容器中的所有元素:
plays = set(['Hamlet', 'Macbeth', 'King Lear'])
while plays:
play = plays.pop()
print('Perform', play)
Perform King Lear
Perform Macbeth
Perform Hamlet
循环每次从 plays
中弹出一个元素,一直到 plays
为空为止。
for 循环
for <variable> in <sequence>:
<indented block of code>
for
循环会遍历完<sequence>
中所有元素为止
上一个例子可以改写成如下形式:
plays = set(['Hamlet', 'Macbeth', 'King Lear'])
for play in plays:
print('Perform', play)
Perform King Lear
Perform Macbeth
Perform Hamlet
使用 for
循环时,注意尽量不要改变 plays
的值,否则可能会产生意想不到的结果。
之前的求和也可以通过 for
循环来实现:
total = 0
for i in range(10):
total += i
print(total)
55
然而这种写法有一个缺点:在循环前,它会生成一个长度为 10
的临时列表。
生成列表的问题在于,会有一定的时间和内存消耗,当数字从 10
变得更大时,时间和内存的消耗会更加明显。
为了解决这个问题,我们可以使用 xrange
来代替 range
函数,其效果与range
函数相同,但是 xrange
并不会一次性的产生所有的数据:
total = 0
for i in xrange(10):
total += i
print(total)
55
比较一下两者的运行时间:
%timeit for i in xrange(10): i = i
10 loops, best of 3: 0.7 ms per loop
%timeit for i in range(10): i = i
10 loops, best of 3: 1.6 ms per loop
可以看出,xrange
用时要比 range
少。
continue 语句
遇到 continue
的时候,程序会返回到循环的最开始重新执行。
例如在循环中忽略一些特定的值:
values = [9, 6, 4, 5, 21, 2, 1]
for i in values:
if i % 2 != 0:
#忽略奇数
continue
print(i/2)
3
2
1
break 语句
遇到 break
的时候,程序会跳出循环,不管循环条件是不是满足:
command_list = ['start',
'process',
'process',
'process',
'stop',
'start',
'process',
'stop']
while command_list:
command = command_list.pop(0)
if command == 'stop':
break
print(command)
start
process
process
process
在遇到第一个 'stop'
之后,程序跳出循环。
else语句
与 if
一样, while
和 for
循环后面也可以跟着 else
语句,不过要和break
一起连用。
- 当循环正常结束时,循环条件不满足,
else
被执行; - 当循环被
break
结束时,循环条件仍然满足,else
不执行。
不执行:
values = [7, 6, 4, 7, 19, 2, 1]
for x in values:
if x <= 10:
print('Found:', x)
break
else:
print('All values greater than 10')
Found: 7
执行:
values = [11, 12, 13, 100]
for x in values:
if x <= 10:
print('Found:', x)
break
else:
print('All values greater than 10')
All values greater than 10
在python里面没有C++的诸多语法,你只要会if判断和for循环就可以做很多事情了。for循环使用的频率是非常搞的,其与if嵌套使用,可以实现绝大部分的逻辑。
The End
OK,今天的内容就到这里,如果觉得内容对你有所帮助,欢迎点赞转发。
如果觉得不错,希望能动动手指转发给你身边的朋友们。