程序的循环结构
程序的循环结构
循环用来干什么:干重复的事
1.for循环
结构:for <循环变量> in <遍历结构>:
<语句块>
从遍历结构中逐一提取元素,放在循环变量中,每次循环,所获得元素放入循环变量并执行
for i in range(100):
print(i)
range(5) #[0,1,2,3,4]
range(1,3) #[1,2]
range(1,10,2) #[1,3,5,7,9]
for i in 'nick':
print(i,end=" ") #n i c k
2.while循环
结构:while <条件>:
<语句块>
反复执行语句块,直到条件不满足时结束
# 周一到周五努力到什么程度才能 == 每天进步0.01
factory = 0.01
base = 0
while base < pow(1.01,365):
factory += 0.001
base = 1
for i in range(365):
if i % 7 == 0:
base *= (1 - 0.01)
if i % 7 == 6:
base *= (1 - 0.01)
else:
base *= (1 + factory)
print(factory)
3.continue + break
break跳出并结束当前整个循环,执行循环后的语句
continue结束当次循环,继续执行后续次数循环
break和continue可以与for和while循环搭配使用
count = 0
while count < 100: # 49
if count == 49:
count += 1
continue # 不执行下面代码,继续运行循环
count += 1 # 50
print(count) # 50
count = 0
while count < 100: # 49
if count == 49:
count += 1
break # 终止循环
count += 1 # 50
print(count) # 50
4.else
count = 0
while count < 100:
if count == 49:
count += 1
break #终止循环
count += 1
print(count)
else: #正常跳出循环的时候执行,异常中断不执行
print('打印')