IF条件控制
条件控制
定义
Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。
如下图所示
IF语句
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区分大小写
>>> s = 'Upper' >>> s == 'upper' False >>> s.lower() == 'upper' True
逻辑判断
表达式 | 描述 |
a == b | a等于b |
a != b | a不等于b |
a > b | a大于b |
a >= b | a大于等于b |
a is b | a和b 是同一个对象 |
a is not b | a和b不是同一个对象 |
a in A | a在A中 |
a not in A | a不在A中 |
逻辑为假的情况
假(False) | 真(TRUE) |
False | True |
None | not None |
0 | not 0 |
''(空) | not '' |
[](空字典) | 字典中有元素 |
()(空元组) | 元组中有元素 |
{}(空字典) | 字典中有元素 |
set() | 集合中有元素 |
形式
if
if - else
if - elif - else
if -elif
if - elif - elif
例子
n = 10
if n > 0: print("%d is 正数" %(n) ) elif n < 0: print("%d is 负数" %(n) ) else: print("%d is 零" %(n)
if 语句中嵌套if语句
n = -10.3 if n > 0: if n % 1 == 0: print("%.1f is 正整数" %(n) ) else: print("%.1f is 正小数" %(n) ) elif n < 0: if n % 1 == 0: print("%.1f is 负整数" %(n) ) else: print("%.1f is 负小数" %(n) ) else: print("%f is 零" %(n) ) #out:-10.3 is 负小数