# Python 教程 - 决策构造

## `if` 声明

`if` 声明中，你只有一个语句块，并且仅当条件为 `True` 时才执行此块，当条件为 `False` 时，将忽略该语句块。

``````if condition:
statement(s)
``````

Python 中的 `if` 语句主体不是用花括号括起来，而是使用缩进。主体的末端由第一条不在同一个缩进水平的行来决定。

### `if` 声明示例

``````a = 24
if a % 2 == 0:
print(a, "is an even number")
b = 23
if b % 2 == 0:
print(b, "is an odd number")
``````
``````24 is an even number
``````

## `if...else` 声明

``````if condition:
block of statements
else:
block of statements
``````

`if...else` 中，如果 `if` 条件为 `True`，则执行相应的语句块，否则将执行 `else` 下的语句块。

### `if...else` 声明示例

``````a = 44
if a%2==0:
print(a, "is an even number")
else:
print(a, "is an odd number")
``````
``````44 is an even number
``````

`if``else` 块不能同时执行或忽略。根据条件是否执行仅执行一个程序段 `True`

## `if...elif...else` 声明

``````if condition:
block of statements
elif condition:
block of statements
else:
block of statements
``````

`elif` 代表 `else if` 它可以在此 `if..elif..else` 构造中多次使用。

`if` 条件为 `False` 时，将检查 `elif` 条件等等。当所有的 `if` 条件和 `elif` 条件是 `False` 时，`else` 部分将被执行。

`if...elif...else` 仅能执行一个程序段。

### `if...elif...else` 声明示例

``````a = -34
if a > 0:
print("Number is Positive")
elif a < 0:
print("Number is Negative")
else:
print("Number is zero")
``````
``````Number is Negative
``````

## 嵌套 `if` 语句

### 嵌套 `if` 语句示例

``````T = 52

if T > 25:
if T < 50:
print("Temperature is higher than 25 but lower than 50")
else:
print("Temperature is higher than 50")
else:
if T < 0:
print("Temperature is lower than 0")
else:
print("Temperature is higher than 0 but lower than 25")
``````
``````Temperature is higher than 50
``````