知识点:
1.while()
2.break # 终止此循环
3.continue # 退出当前循环,执行下次循环
4.for循环
5.for…else
5.while…else
while循环
# while循环
i = 0
while i < 5:
print(f"i={i}")
i += 1
print("任务结束")
求 1到100的累加和
# 求 1到100的累加和
i = 1
sum = 0
while i <= 100:
sum += i
i = i+1
print(f"i:{i}, sum:{sum}")
求 1到100的偶数累加和 方法1:
# 求 1到100的偶数累加和 方法1:
i = 1
sum = 0
while i <= 100:
if i % 2 == 0:
sum += i
i = i+1
print(f"i:{i}, sum:{sum}")
求 1到100的偶数累加和 方法2:
# 求 1到100的偶数累加和 方法2:
i = 2
sum = 0
while i <= 100:
sum += i
i = i+2
print(f"i:{i}, sum:{sum}")
break 终止此循环
吃苹果
# break 终止此循环
# 吃苹果
i = 1
while i < 8:
print(f'吃了第{i}个苹果')
if i == 4:
print("吃饱了,不吃了")
break
i += 1
continue 退出当前循环,执行下次循环
# continue 退出当前循环,执行下次循环
i = 1
while i < 8:
print(f'吃了第{i}个苹果')
if i == 4:
print("吃出一个大虫子,这个苹果不吃了")
# 如果使用了continue,在continue之前一定要修改计数器,否则进入死循环
i += 1
continue
i += 1
while循环嵌套的样例:
1.媳妇儿,我错了
# 1.媳妇儿,我错了
i = 0
while i < 3:
j = 0
while j < 3:
print("媳妇儿,我错了")
j += 1
print("刷今晚的碗")
print("一套惩罚结束--------")
i += 1
2.打印星号(方形)
# 2.打印星号(方形)
j = 0
while j < 5:
i = 0
while i < 5:
print('*', end='')
i += 1
# 一行星星结束,换行显示下一行
print()
j += 1
3.打印星号(三角形)
# 3.打印星号(三角形)
j = 0
while j < 5:
i = 0
while i <= j:
print('*', end='')
i += 1
print()
j += 1
4.打印九九乘法表
# 4.打印九九乘法表
i = 1
while i <= 9:
j = 1
while i >= j:
print(f'{j}*{i}={i * j}', end='\t')
j += 1
print()
i += 1
for循环
# for循环
str1 = 'hello python'
for i in str1:
print(i)
for循环中使用break 或者 continue
# for循环中使用break 或者 continue
str1 = 'hello python'
for i in str1:
if i == 'o':
break
# continue
print(i)
for…else…
"""
# for循环
for 临时变量 in 序列:
重复执行的代码1
重复执行的代码1
...
else:
for不满足,执行的代码
"""
# for...else...
str1 = "hi python"
for i in str1:
if i == 'y':
print("遇到y不打印")
continue
else:
print(i)
else:
print("hi")
while…else
"""
# while...else
while 条件:
条件成立重复执行的代码
else:
循环正常结束之后要执行的代码
"""
i = 1
while i <= 5:
print("媳妇儿,我错了")
i += 1
else:
print("媳妇儿原谅我了")
continue / break 在while中的使用
# continue在while中的使用
i = 1
while i <= 5:
if i == 3:
print("这遍说的不真诚")
i += 1
continue
# break
print("媳妇儿,我错了")
i += 1
else:
print("媳妇儿原谅我了")