4.3 循环结构

4.3.1 for循环与while循环

``````a_list = ['a','b','mp','z','example']
for i,v in enumerate(a_list):
print('列表的第',i+1,'个元素是：',v)
``````
``````列表的第 1 个元素是： a

``````
• 九九乘法表
``````for line in range(1,10):
for row in range(1,line+1):
print(line*row,end=" ")
print( )
``````
``````1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
``````
``````for i in range(1,10):
for j in range(1,i+1):
print('{0}*{1}={2}'.format(i,j,i*j),end=' ')
print( )
``````
``````1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
``````

4.3.2 break与continue语句

• 判断一个数是否为素数
``````n = input('输入一个数')
n = int(n)
for i in range(2,n):
if n % i == 0:
print('{}不是素数'.format(n))
break
else:
print('{}是素数'.format(n))
``````
• 计算小于100的最大素数
``````for n in range(100,1,-1):
'''if n%2 == 0:
continue'''
for i in range(3,int(n**0.5)+1,2):  #代码优化，平方根间的奇数范围更小
if n % i == 0:
break
else:
print(n)
break
``````
``````97
``````

4.3.3 循环代码优化技巧

• 尽量减少内层循环中不必要的计算，把计算向外提
• 见下例子 第二段比第一段效率高
``````digits = (1,2,3,4)
for i in range(1000):
result = []
for i in digits:
for j in digits:
for k in digits:
result.append(i*100+j*10+k)
``````
``````for i in range(1000):
result = []
for i in digits:
i = i*100
for j in digits:
j = j*10
for k in digits:
result.append(i+j+k)
``````
• 局部变量的查询和访问速度比全局变量略快
• 见下例子 第二段的速度略快于第一段
``````import math
for i in range(10000000):
math.sin(i)
``````
``````loc_sin = math.sin
for i in range(10000000):
loc_sin(i)
``````