2019-02-25
(1)break语句:终止当前循环,跳出循环体。
(2)continue语句:终止本轮循环并开始下一轮循环(在下一轮循环开始前,会先测试循环条件)。
(3)for循环
① range()函数:
1) 语法:rang([start,]stop[,step = ?]) 表示从start参数的值开始,到stop参数的值结束,step= ?表示步长。
2) range(3),生成0~2之间的所有的数字。
② for后面可以加else
测试代码:
exit_flag = False for i in range(10): if i < 5: continue print("外层循环:",i) for j in range(10): if j == 5: exit_flag = True break print("内层循环:",j) if exit_flag == True: break
运行结果:
外层循环: 5 内层循环: 0 内层循环: 1 内层循环: 2 内层循环: 3 内层循环: 4
(4)while循环
① 语法 while 条件:
循环体
当条件为真时,执行循环语句,否则退出循环。
测试代码:
_age = 22
counter = 0
while counter < 3:
user_age = int(input("user_age:"))
if _age == user_age:
print("you are right!!!")
break
else:
print("you are wrong!!!")
counter +=1
else:
print("you shouldn't input")
运行结果:
user_age:22
you are right!!!
user_age:33 you are wrong!!! user_age:34 you are wrong!!! user_age:35 you are wrong!!! you shouldn't input