### 文章目录
- [@[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... 语句。