三元运算符

发布时间 2023-12-12 18:29:43作者: ssrheart

三元运算符

  • 为真时的结果 if 返回布尔值的判断条件 else 为假时的结果
a = 20
b = 30

print(a if a < b else b)  # 20
print({True: a, False: b}[a < b])  # 20
print((b, a)[a < b])  # 20

a, b = 10, 20

print("Both a and b are equal" if a != b else (
    "a is greater than b" if a > b else "b is greater than a"))  # Both a and b are equal
print("a is greater than b" if a > b else "b is greater than a")  # "b is greater than a"