Python implements the question mark expression of? The method of

  • 2020-04-02 13:15:59
  • OfStack

And and or in python are very different from other languages
And and or in other languages are results that return a bool type; python is not. It returns one of the values that do the and and or operation.
That value determines the value of this expression, and that value is returned.


>> 5 and ''

The result here is "", an empty string, because that's what caused this expression to be false.
That is, in and, it is only possible to be a result if the previous value is false. Otherwise, the final value is the result.

Now that you understand how and and or work, you can implement it. Right? The expression:


if (expression):
     return truevalue
else:
    return falsevalue

The equivalent of this is (similarly? ):


expression and truevalue or falsevalue
# or 
(expression and (truevalue,) or (falsevalue,))[0] # Thank you for snake117 Advice provided 
# This is to avoid truevalue It is possible that false , such as an empty string 


Related articles: