简体   繁体   中英

python 3 boolean logic shortcut

I have code that looks something like this:

x = someIntValue
if y is None:
    y = x

elif x < y:
    y = x

Is there a shorter way of doing this? eg, something like: y = x if x < y or not y ?

the issue is that y can be None and or a number

Since the end results for both the condition is same, you can combine them into one if.

if y is None or x < y :
    y = x

As explained by @Giacomo in comments, a one liner version for this can be (since y is already defined)

y = x if ( y is None or x < y ) else y

You cannot write this exactly using a conditional expression , as y do not get assigned at all in the case that both boolean expressions are False (well, if you are willing to reassign y to itself, you can). You can or course get by without the elif :

x = someIntValue
if y is None or x < y:
    y = x

(I presume that y also has a value prior to this).

Your x < y or not y is bad for two reasons. First, it evaluates x < y before not y , which fails if y is None . Second, not y is not logically equivalent to y is None . For example, for y = 0 , not y results in True while y is None results in False .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM