三元运算符

三元运算符

  • 为真时的结果 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"

本文作者:ssrheart

本文链接:https://www.cnblogs.com/ssrheart/p/17897563.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   ssrheart  阅读(10)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起