Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if x>y without if statement

In Python, is it possible to check whether x>y without using the if statement?


2 Answers

There are a variety of ways to go about this:

print "yes" if x > y else "no"

or:

print ["no", "yes"][x > y]

or:

print x > y and "yes" or "no"

(at least, this is what my mind-reading powers think that you're doing)

>>> x=1
>>> y=2
>>> "YNEOS"[x<y::2]
'NO'
>>> x=3
>>> "YNEOS"[x<y::2]
'YES'
like image 32
John La Rooy Avatar answered Aug 25 '26 23:08

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!