Python Ternary Operator Without else

后端 未结 7 847
执笔经年
执笔经年 2020-11-29 00:36

Is it possible to do this on one line in Python?

if :
    myList.append(\'myString\')

I have tried the ternary operator:

7条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:01

    The reason the language doesn't allow you to use the syntax

    variable = "something" if a_condition
    

    without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.

    Similarly, all returns must actually return, even if they are conditional returns. Eg:

    return variable if a_condition
    

    is not allowed, but

    return variable if a_condition else None
    

    is allowed, since the second example is guaranteed to explicitly return something.

提交回复
热议问题