要点概括:

ConditionalControl-contents

1.if 语句

if语句的格式如下:

1
2
3
4
5
6
if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

在 Python 中,用elif代替了其他语言(C、Java)中的else if,具体为:

  • 如果condition_1True,则执行statement_block_1内的语句;如果condition_1False,则判断condition_2
  • 如果condition_2True,则执行statement_block_2内的语句;如果condition_2False,则执行statement_block_3内语句。

下面展示一个简单的例子,如下所示:

1
2
3
4
5
6
7
a = 1
b = 2
if a < b:
    print('a is less than b')
else:
    print('a is not less than b')
print('outside the if block')

输出结果如下:

1
2
a is less than b
outside the if block

可以看到,由于a小于b,所以判断条件a < b的结果为True,接着输出a is less than b。因为最后一条语句print('outside the if block')if语句之外,或者说与if语句没有关系,所以自然就输出了outside the if block

接下来看下面一个例子,如下所示:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
c = 20
d = 8
if c < d:
    print('c is less than d')
elif c == d:
    print('c is equal to d')
elif c > d + 10:  # 此时d的值为18
    print('c is greater than d by more than 10')
else:
    print('c is greater than f')

输出结果如下:

1
c is greater than d by more than 10

你也可以通过给cd不同的值来得出不同的结果。

2.if 嵌套

下面给出嵌套的 if 语句,如下所示:

1
2
3
4
5
6
7
8
9
e = 8
f = 8
if e < f:
    print('e is less than f')
else:
    if e == f:
        print('e is equal to f')
    else:
        print('e is greater than f')

输出结果如下:

1
e is equal to f

首先判断e < f是否成立,因为9 < 8不成立,所以返回结果为False,之后不执行print('e is less than f'),反而进入else代码块中,在这里面接着判断e == f,结果为True,所以最终输出e is equal to f