Python学习记录: 三元运算符

2019-11-13  本文已影响0人  R_zb

用法一

# 例子1
a = 1
b = 2
c = a-b if a>b else a+b
print(c) # c的值为3

"""
# 
if a>b:
    c = a-b
else:
    c = a+b
"""

# 例子2
a = True
b = "hi" if a else "hello"
print(b) # 输出:hi

"""
if a==True:
    b = "hi"
else:
    b = "hello"
"""

用法二

a = True
b = ("aa","bb")[a]
print(b)    # "bb"

c = (11,22)[False]
print(c)    # 11


上一篇 下一篇

猜你喜欢

热点阅读