检查x> y是否没有if语句

0 python if-statement

在Python中,是否可以在不使用if语句的情况下检查x> y?

小智 10

有很多方法可以解决这个问题:

print "yes" if x > y else "no"
Run Code Online (Sandbox Code Playgroud)

要么:

print ["no", "yes"][x > y]
Run Code Online (Sandbox Code Playgroud)

要么:

print x > y and "yes" or "no"
Run Code Online (Sandbox Code Playgroud)

(至少,这是我的思维阅读能力认为你正在做的事情)

  • 第一个解决方案使用if :) (4认同)
  • ......但不作为陈述:p (2认同)
  • @Gustavo:这个问题与Python中的if语句有关,而与机器代码无关. (2认同)

Joh*_*ooy 6

>>> x=1
>>> y=2
>>> "YNEOS"[x<y::2]
'NO'
>>> x=3
>>> "YNEOS"[x<y::2]
'YES'
Run Code Online (Sandbox Code Playgroud)