python中三元运算符的使用

三元表达式

1. 结果1 if 条件 else 结果2

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

a = 1
b = 2
# 给变量赋值
msg = "大于" if a > b else "小于"
print(msg)

# 输出表达式
print('大于') if a > b else print("小于")
小于
小于

2. (结果2, 结果1)[判断表达式]

结果2为判断表达式为False的值,结果1为判断表达式True的值

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

a = 1
b = 2
# 给变量赋值
msg = ("a小于b", "a大于b")[a > b]
print(msg)    
a小于b

3. {条件值1:结果1, 条件值2:结果2}[判断表达式]

有点类似java中的switch, case表达式

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

a = 1
b = 2
# 给变量赋值
msg = {
     2: '=2', 1: '=1', 3: '=3'}[b - a]
print(msg)
# 如果变量表达式的值没有定义,会出现KeyError
msg = {
     2: '=2', 1: '=1', 3: '=3'}[a - b]
print(msg)
=1
Traceback (most recent call last):
  File "D:/CATS/Code/tools/extrafunction/PyClusterTool/utils/test.py", line 9, in 
    msg = {2: '=2', 1: '=1', 3: '=3', None: '=None'}[a - b]
KeyError: -1

你可能感兴趣的:(Python)