(二)Python基本语句

### 文章目录

  • [@toc](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [条件语句if .. else ..](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [循环语句](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [for 循环](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [while循环](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [break](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [continue](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)
  • [pass](#文章目录 @[toc] 条件语句if .. else .. 循环语句 for 循环 while循环 break continue pass)

条件语句if ... else ...

在进行逻辑判断时,需要用到条件语句,Python提供了if/elif/else进行逻辑判断,elif是else if的缩写,python中采用elif作为关键字。如下所示。

python 复制代码
if 判断条件1:
    执行语句1
elif 判断条件2:
    执行语句2
elif 判断语句3:
    执行语句3
else:
    执行语句4

循环语句

for 循环

for循环可以循环任何序列,如字符串、列表、字典等。

python 复制代码
str = "Python"
for s in str:
    print(s)  

输出结果为:

复制代码
P
y
t
h
o
n

while循环

while循环为条件满足时进行循环,不满足则退出循环。

python 复制代码
# 求10到1的和
sum = 0
m = 10
while m > 0:
    sum += m  # sum = sum +m
    m -= 1  # m = m-1
print(sum)

break

在循环过程中,往往想要通过某种条件起到终止整个循环的作用。

python 复制代码
str = "Python"
for s in str:
    if s == "o":  # 当字符是o时,终止循环
        break
    print(s)

输出结果为:

复制代码
P
y
t
h

continue

再循环过程中,往往想要通过某种条件起到终止本次循环的作用。

python 复制代码
str = 'Python'
for s in str:
    if s == 'o':   # 当字符为o时 跳过输出 继续循环
        continue
    print(s)

输出结果为:

复制代码
P
y
t
h
n

举一个简单的例子,当遍历图像并获取其对应的标注文件时,当该图像的标注文件不存在,那应该跳过该图像标注文件的读取过程,继续后续图像标注文件的读取。

pass

pass是空语句,他不做任何事情,一般只做占位语句,作用是保持程序结构的完整新。

python 复制代码
str = 'Python'
for s in str:
    if s == 'o': 
        pass
    print(s)

一般用于编写过程中的debug, 上述例子中,当字符是o是,后续的内容还没想好怎么写,但是想要debug看看各个变量的值时多少,那为了保持整个程序的完整性,并且执行不会报错,可以使用pass。

Python中没有switch... case... 以及do... while... 语句。

相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github