(二)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... 语句。

相关推荐
允许部分打工人先富起来32 分钟前
在node项目中执行python脚本
前端·python·node.js
IVEN_36 分钟前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend1 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽2 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_19 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang21 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮21 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling21 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维