一. 条件判断
条件判断的关键字if elif else,具体规则如下:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- 如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
- 如果 "condition_1" 为False,将判断 "condition_2"
- 如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
- 如果 "condition_2" 为False,将执行"statement_block_3"块语句
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。
注意:
- 1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。
- 2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
- 3、在Python中没有switch – case语句。
以下为if中常用的操作运算符:
操作符 | 描述 |
---|---|
< |
小于 |
<= |
小于或等于 |
> |
大于 |
>= |
大于或等于 |
== |
等于,比较对象是否相等 |
!= |
不等于 |
if语句也还可以嵌套:
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
二. 循环语句
循环语句有两种,一种是for ... in,还有一种是while。
Python循环语句的控制结构图如下所示:
第一种for ... in,Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
第二种是while,一般形式如下:
while 判断条件:
语句
在Python中没有do..while循环。
在 while … else 在条件语句为 false 时执行 else 的语句块。和for循环一样。
三. break,continue和pass
break是跳出循环体。到这就结束循环了。p
continue只是结束当前循环,接着做下一轮的循环。
pass是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。
四. 三元表达式
true_part if condition else false_part 或者 condition and true_part or false_part两种。
true_part if condition else false_part:
>>> 1 if True else 0
1
>>> 1 if False else 0
0
>>> "Fire" if True else "Water"
'Fire'
>>> "Fire" if False else "Water"
'Water'
condition and true_part or false_part:
>>> True and 1 or 0
1
>>> False and 1 or 0
0
>>> True and "Fire" or "Water"
'Fire'
>>> False and "Fire" or "Water"
'Water'
但是遇到空字符串的时候,处理有些不一样,请看例子:
>>> True and "" or "Water"
'Water'
返回的值是false_part。
如果想取空字符串,可以这样做:
>>> a = ""
>>> b = "Water"
>>> (True and [a] or [b])[0]
''