循环的作用
while循环
while 条件:条件成立重复执行的代码1条件成立重复执行的代码2......
break和continue
break的用法
continue的用法
- 用于跳过本次循环余下的语句,转去判断是否需要继续执行下次循环;
- 在使用
**continue**之前,一定要加入计数器变量,防止出现死循环。 ```python i = 1 while i <= 5: if i == 3:
print(f”我吃到了第{i}个苹果了!”) i += 1print("有大虫子,不要这个苹果了!!!")i += 1 # continue之前要加入计数器变量,防止进入死循环continue
<a name="LymHo"></a># `while`循环嵌套```pythonwhile 条件1:条件1成立执行的代码......while 条件2:条件2成立执行的代码......
while嵌套举例
""" 九九乘法表实现 """i = j = 1while j <= 9: # 行while i <= j: # 列print(f"{i}*{j}={i * j}", end="\t")i += 1j += 1i = 1print() #换行
for循环遍历
for 临时变量 in 序列:重复执行的代码1重复执行的代码2......
for循环遍历举例
str = "abcdef"for i in str: # for循环遍历----i为str的索引,i每次循环会自增1print(i, end="") # 打印字符print()
for循环遍历与break
str = "abcdef"for i in str:if i == "c":print()print("**检测到c,停止打印!**", end="")break # 跳出for循环print(i, end="")print()
for循环遍历与continue
str = "abcdef"for i in str:if i == "c":print()print("**检测到c,跳过!**", end="")print()continueprint(i, end="")print()
循环中的else组合
while...else...
while 条件:条件成立重复执行的代码else:循环正常结束后要执行的代码
break对while...else组合的影响
age = int(input("请输入你的年龄: "))while age < 18:print("核验结果:未成年!")break # break执行后,else的代码不执行(else是while循环体的一部分)else:print("核验结果:已成年!")
continue对while...else组合的影响
i = 1while i <= 5:if i == 3:i += 1continue # continue执行后,else的代码在while退出后执行print("hello")i += 1else:print("world")
for...else...
for 临时变量 in 序列:重复执行的代码......else:循环正常结束后要执行的代码
break和continue对for...else组合的影响
同上。
**break**执行后,循环中断,**else**作为循环体的一部分不会被执行;**continue**执行后,**else**的代码在**for**循环退出后执行。
