Python三元运算

Python三元运算

Python没有类似与C语言系列的三元运算符<condition> ? <expression1>: <expression2>,但可以通过<condition> and <expression1> or <expression2>或者<expression1> if <condition> else <expression2>方式实现三元运算。关于Python三元运算,Python社区很早就开始讨论了[1]
具体使用如下:
and/or使用

result1 = True and 'test_true' or 'test_false'    # result1 = test_true
s = 1
result2 = s == 2 and 'test_true' or 'test_false'    # result2 = test_false

if/else使用

result1 = 'test_true' if True else 'test_false'    # result1 = test_true
s = 1
result2 = 'test_true' if s == 2 else 'test_false'    # result2 = test_false

在使用and/or时需要特别注意,虽然and/or比较简洁,但容易出错比如

result1 = True and False or True    # result1 = True
s = 1
result2 = s !=1 and False or True   # result2 = True
s = 2
result3 = s !=1 and False or True   # result3 = True

因此进行三元运算时,建议使用if/else

参考引用

[1] PEP 308 – Conditional Expressions

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值