5 循环控制
1. While 循环
语法
while 条件: 执行代码...
简单吧, while
就是当的意思,当山峰没有棱角的时候,当河水。。。,sorry , while
指 当其后面的条件 成立 ,就执行while
下面的代码
- 从0打印到100的程序 ,每循环一次,+1
count = 0 while count <= 100: # 只要count<=100就不断执行下面的代码 print("loop", count) count += 1 # 每次执行一次,就把count+1 不然就是死循环了,因为count一直是0 print("----loop end-----")
count = 0 while count <= 100: if count % 2 == 0: # 取模运算 print("loop", count) count += 1 print("----loop end-----") #运行结果 loop 34 loop 36 loop 38 loop 40 loop 42 loop 44
loop 49 loop 51 loop 52 loop 53 loop 54 loop 55 loop 56 loop 57 loop 58 loop 59 loop 3600 loop 3721 loop 3844 loop 3969
2.死循环:dead loop
有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。
while 是只要后边条件成立(也就是条件结果为真)就一直执行,怎么让条件一直成立呢?
count = 0 while True: #True本身就是真呀 print("你是风儿我是沙,缠缠绵绵到天涯...",count) count +=1
3.循环中止语句
如果在循环的过程中,因为某些原因,你不想继续循环了,怎么把它中止掉呢?这就用到break 或 continue 语句
- break用于完全结束一个循环,跳出循环体执行循环后面的语句
- continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环
1)break例子
count = 0 while count <= 100 : #只要count<=100就不断执行下面的代码 print("loop ", count) if count == 5: break count +=1 #每执行一次,就把count+1,要不然就变成死循环啦,因为count一直是0 print("-----out of while loop ------")
# 运行结果 loop 0 loop 1 loop 2 loop 3 loop 4 loop 5 ---out of while loop--
2) continue例子
loop 0 loop 1 loop 2 loop 3 loop 4 loop 5 loop 5 loop 5 loop 5 loop 5 loop 5 # 一直循环下去 ...
3)continue例子2
count = 0 while count <= 100: count += 1 if count > 5 and count < 95 : continue print("loop",count) # 运行结果 loop 1 loop 2 loop 3 loop 4 loop 5 loop 95 loop 96 loop 97 loop 98 loop 99 loop 100 loop 101
3 猜年龄
(1)练习1
# 运行结果 Guess age:11 try bigger Guess age:27 you got it Guess age:11 try bigger Guess age:22 try bigger Guess age:33 try smaller please go back
(2)练习2 版本1
#运行结果 Guess age:11 try bigger Guess age:22 try bigger Guess age:33 try smaller please go back you want go ? y|ny
(3)练习2 版本2
(4)老师版本
# 运行结果 Guess age:2 try bigger Guess age:2 try bigger Guess age:2 try bigger you want go ? y|Yy Guess age:1 try bigger Guess age:1 try bigger Guess age:1 try bigger you want go ? y|YY Guess age:27 you got it
4 while...else 玩法
与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句
while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句