循环语句:while
1. while语句结构:while+条件
-
示例1:
while True: print("人生苦短,我用Python。")
运行得到的结果是循环打印“人生苦短,我用python。”
-
示例2:
while 1>0 and 2>1: print("人生苦短,我用Python。")
运行得到的结果也是循环打印“人生苦短,我用python。”
-
示例3
通过循环,让count每次都+1count = 1 while True: print(count) count = count + 1
运行得到的结果是,从1开始每次循环+1
-
示例4
通过循环,打印从1到10count = 1 while count <= 10: print(count) count = count + 1 print("结束")
运行结果
-
示例5
通过循环,打印从1、2、3、4、5、6、8、9、10# 我的方法 count = 1 while count <= 10: print(count) count = count + 1 if count == 7: count = count +1 print("结束")
运行结果
其他方法同样可以实现:
# 其他同学的方法 count = 1 while count <= 6: print(count) count = count + 1 count = 8 while count <= 10: print(count) count = count + 1 # 老师的方法1 count = 1 while count <= 10: if count != 7: print(count) count = count + 1 print("结束") # 老师的方法2 count = 1 while count <= 10: if count == 7: pass else: print(count) count = count + 1 print("结束")
2. 关键字:break
break,跳出当前循环
-
示例1
count = 1 while count <= 10: if count == 7: break print(count) count = count + 1 print("结束")
运行结果
-
示例2:通过break实现,打印1~10
count = 1 while True: print(count) if count == 10: break count = count + 1 print("结束")
运行结果
3. 关键字:continue
continue,本次循环如果遇到continue,则不再继续向下运行,回到while条件位置
-
示例:使用continue,打印1,2,3,4,5,6,8,9,10
# 方法1 count = 1 while count <= 10: if count == 7: count += 1 # count += 1 ; 等效于:count = count + 1 ; continue print(count) count += 1 print("结束") # 方法2 count = 1 while count <= 10: print(count) if count == 6: count += 2 continue count += 1 print("结束")
运行结果
4. while else
用的比较少:else在不满足while条件,或者条件为false时触发
-
示例1
count = 1 while count <= 10: print(count) count = count + 1 else: print("正常完成") print("结束")
运行结果
-
示例2
count = 1 while count <= 10: print(count) if count == 7: break count = count + 1 else: print("正常完成") print("结束")
运行结果
因为count=7时,执行了break,跳出循环,而非while的条件不满足,因此else未执行