(二)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 小时前
mathmodel-figure-templates 以及两个上手案例
后端·python
fengci.1 小时前
CTF2MISC中等部分
开发语言·前端·学习
锋行天下2 小时前
服务器 Python 2.7 装不了 langgraph-cli?用本地生成 Dockerfile 曲线救国
人工智能·后端·python
一条大祥脚2 小时前
深入理解 PyTorch FlexAttention:从 Score Mod 到 Mask Mod 的稀疏加速之道
人工智能·pytorch·python·注意力机制·flex attention·可编程注意力
xys_6782 小时前
JavaEE通关手册:初识Java
java·开发语言
2601_967980113 小时前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
长沙三为智能科技3 小时前
GEO与传统SEO的5个关键差异:排名与被引用、关键词与答案型的全维度对比
python·aigc·seo·ai搜索·geo优化
ShineWinsu3 小时前
对于Qt:QTableWidget常见属性以及QTableWidgetItem类的解析
开发语言·c++·qt·gui·客户端·表格·qtablewidget
量化分析码农4 小时前
【Python量化趋势跟踪实战 02】突破买入总被假突破坑:通道系统与入场时机
python
Agent世界4 小时前
多平台登录态巡检:cookie 判据为什么会撒谎
python