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

相关推荐
ONE_SIX_MIX2 小时前
qwenpaw-plugin-file-tools QwenPaw增强文件工具 更新 v1.1.1
python·qwenpaw
AOwhisky2 小时前
Python 学习笔记(第五期)——组合数据类型:列表、元组、集合与字典精讲——核心知识点自测与详解
开发语言·笔记·python·学习·云计算
码农学院2 小时前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
程序员羽痕2 小时前
基于 Django + PyTorch 的中文字体识别系统
pytorch·python·django
灯澜忆梦11 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-11 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-12 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白13 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧13 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
段一凡-华北理工大学15 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化