谁还没个明天 2008-12-27 08:32 采纳率: 50%
浏览 579
已采纳

是否有一个条件运算符?

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

转载于:https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator

  • 写回答

14条回答 默认 最新

  • MAO-EYE 2015-11-23 18:56
    关注

    Yes, it was added in version 2.5.
    The syntax is:

    a if condition else b
    

    First condition is evaluated, then either a or b is returned based on the Boolean value of condition
    If condition evaluates to True a is returned, else b is returned.

    For example:

    >>> 'true' if True else 'false'
    'true'
    >>> 'true' if False else 'false'
    'false'
    

    Note that conditionals are an expression, not a statement. This means you can't use assignments or pass or other statements in a conditional:

    >>> pass if False else x = 3
      File "<stdin>", line 1
        pass if False else x = 3
              ^
    SyntaxError: invalid syntax
    

    In such a case, you have to use a normal if statement instead of a conditional.


    Keep in mind that it's frowned upon by some Pythonistas for several reasons:

    • The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
    • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
    • Stylistic reasons.

    If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

    Official documentation:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧