#!/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
为判断表达式为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
有点类似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