循环
什么叫做循环
循环:出自于《战国策》,周而复始,则谓之为循环。
因此循环,就是重复执行某些代码。
在真实的企业中,不要重复粘贴复制代码,因为将来代码的维护成本很高。所以开发者需要一种能够重复执行某些代码的一种语法。
python中,只存在两种循环。
-
for 设计之初,主要用来解决无序数据迭代问题
-
while 常规的循环
while循环
语法结构:
while condition: # 循环体 [else: # 表示循环正常结束时,才会进入到else ]
案例1:打印输入100行“hello world”。
index = 0 while index < 100: print("hello wrold", index + 1) index += 1 print("game over")
循环的注意事项:
-
循环必须存在条件
-
如果条件永远成立,则是死循环
-
循环的条件应该有个极限值
案例2:使用while循环球0~100的和。
index = 0 count = 0 while index <= 100: count += index index += 1 print(f"0~100的和是:{count}")
案例3: 求100!。
index = 1 count = 1 while index <= 100: count *= index index += 1 print(f"100的阶乘是:{count}")
break、continue关键字
-
break 打断、中断,循环表示终止、打断循环
-
continue 继续 , 循环中表示跳过本次循环,进入下次循环
index = 10 while index >= 0: if index == 5: # 终止里它最近的那层循环 break print(index) index -= 1
结论:break会终止循环,默认终止里它最近的那层循环。
index = 10 while index >= 0: index -= 1 if index == 5: # 终止里它最近的那层循环 # break continue print(index)
结论:跳过本次循环,进入下次循环。continue没有终止循环的功能。
循环else
while condition: # 循环体 [else: # 表示循环正常结束时,才会进入到else ]
循环中的else,可以写,也可以不实现(根据具体情况而言)。
else中的代码会不会执行,根据循环是否正常结束来判断,只有循环正常结束,才会进入else块,执行这儿代码。如果循环异常结束【break关键字】,则不会执行else中代码。
index = 10 while index >= 0: index -= 1 if index == 5: # 终止里它最近的那层循环 # break continue print(index) else: print("else是循环正常结束后才执行") print("这段代码执行了吗?") print("GAME OVER")
课堂案例1:在控制台使用while循环输出九九乘法表。
课堂案例2:用户决定打印多少层
""" * ** *** **** ***** """ layer = int(input("请输入您要打印的层数:")) """ 矩形 """ # index = 1 # while index <= layer: # print("*************") # index += 1 """ 直角三角形 """ # index = 1 # while index <= layer: # j = 0 # while j < index: # print("*", end="") # j += 1 # print() # index += 1 index = 1 while index <= layer: print("*" * index) index += 1
作业
1.作业案例
2. 九九乘法表的打印