[Python学习篇] Python循环语句

while 循环

语法:

while 条件:

条件成立后会重复执行的代码

......

示例1:死循环

python 复制代码
# 这是一个死循环示例
while True:
    print("我正在重复执行")

示例2:循环指定次数

python 复制代码
i = 1
while i <= 5:
    print(f"执行次数 {i}")
    i += 1

break 终止当前循环

从break当前行终止代码,break后面的代码不执行

python 复制代码
i = 0
while True:
    i += 1
    if i > 5:
        break
    print("执行")

print("循环已结束")

continue 跳过当前循环

从continue跳过当前本次循环,continue后面的代码不执行,继续下一次循环

python 复制代码
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(f"i = {i}")

for 循环

语法:

for 临时变量 in 序列:

重复执行的代码1

重复执行的代码2

......

示例:

python 复制代码
str1 = 'hello world'
for s in str1:
    print(s)

while...else

语法:

while 条件:

条件成立重复执行的代码

else:

循环正常结束之后要执行的代码

注意:break终止的循环不会执行else块中的代码,continue会执行else块中代码。

示例1:循环正常结束

python 复制代码
i = 0
while i < 5:
    i += 1
    print(i)
else:
    print('循环正常结束')

示例2:循环非正常结束 break

python 复制代码
i = 0
while i < 5:
    i += 1
    if i == 3:
        break
    print(i)
else:
    print('循环正常结束')

示例3:循环正常结束 continue

python 复制代码
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)
else:
    print('循环正常结束')

for...else

语法:

for 临时变量 in 序列:

重复执行的代码

......

else:

循环正常结束之后要执行的代码

......

注意:break终止的循环不会执行else块中的代码,continue会执行else块中代码。

示例1:循环正常结束

python 复制代码
str1 = 'hello'
for s in str1:
    print(s)
else:
    print('循环正常结束')

示例2:循环非正常结束 break

python 复制代码
str1 = 'hello'
for s in str1:
    if s == 'l':
        break
    print(s)
else:
    print('循环正常结束')

示例3:循环正常结束 continue

python 复制代码
str1 = 'hello'
for s in str1:
    if s == 'l':
        continue
    print(s)
else:
    print('循环正常结束')
相关推荐
郝学胜-神的一滴15 分钟前
Effective Python 第44条:用纯属性与修饰器取代旧式的 setter 与 getter 方法
开发语言·python·程序人生·软件工程
嫂子的姐夫1 小时前
11-py调用js
javascript·爬虫·python·网络爬虫·爬山算法
图亚Vanta2 小时前
Python入门第一课:Python安装、VSCode/Pycharm配置
vscode·python·pycharm
睿思达DBA_WGX2 小时前
使用 python-docx 库操作 word 文档(2):在word文档中插入各种内容
python·word
kunge1v53 小时前
学习爬虫第五天:自动化爬虫
爬虫·python·自动化
m***记3 小时前
Python 自动化办公的 10 大脚本
windows·python·自动化
人间乄惊鸿客3 小时前
python - 第二天
python
江上月5134 小时前
django与vue3的对接流程详解(上)
后端·python·django
老歌老听老掉牙4 小时前
基于 PyQt5 实现刀具类型选择界面的设计与交互逻辑
python·qt·交互
可触的未来,发芽的智生4 小时前
触摸未来2025.10.09:记忆的突围,从64个神经元到人工海马体神经网络
人工智能·python·神经网络·机器学习·架构