2015-02-11 57 views
-5

我百思不得其解,为什么-1大于0 这是我的测试程序在蟒蛇2.6.6,为什么是整数-1大于0

> cat logtest.py 
def myfunc(): 
    if -1 > 0: 
     return False 
    else: 
     return True 

if myfunc(): 
    print "True" 
else: 
    print "False" 
> python -V 
Python 2.6.6 
> python logtest.py 
True 

如果我这样做的解释,我得到了不同的结果:

Python 2.6.6 (r266:84292, Apr 11 2011, 15:50:32) 
[GCC 4.4.4 20100726 (Red Hat 4.4.4-13)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> if -1 > 0: 
... print "Whoa!" 
... else: 
... print "unWhoa!" 
... 
unWhoa! 

谢谢!

+3

如果打印TRUE;这意味着-1> 0是错的!再次检查你的代码,你在'else'块中返回'True'。一切工作正常。 – Selcuk 2015-02-11 12:02:46

+1

为什么你不只是在这里返回'-1> 0'?那*已经是一个布尔值*。这样你就不会混淆你的布尔值。 – 2015-02-11 12:07:19

回答

1

您正在返回False-1 > 0是真实的,反之亦然:

>>> if -1 > 0: 
...  print 'True, the universe is indeed upside down!' 
... else: 
...  print 'False, order has been restored' 
... 
False, order has been restored 

,但你这样做:

if -1 > 0: 
    return False 
else: 
    return True 

,所以你基本上是这样做的:

>>> not -1 > 0 
True 

测试结果,返回False当测试结果是真,True当测试结果是假的,但您的控制台测试不匹配的逻辑。在那里你只看到了测试结果本身。

您的错误源于执行表达式已经产生布尔值后显式返回布尔值。这很容易弄错,而你不需要这样做。刚刚回归的表达本身

def myfunc(): 
    return -1 > 0 

print myfunc() 
+0

的确,谢谢。把我的鞋带绑在一起,摔倒了。 – 2015-02-11 15:41:48

0

您的代码工作正常。你似乎误解了逻辑。 -1 > 0的计算结果为False,因此我们预计会提供else区块。

if -1 > 0: 
    print "-1 IS greater than 0" 
else: 
    print "-1 IS NOT greater than 0" 

# -1 IS NOT greater than 0 

试试这个简单的例子:

print -1 > 0 
# False 
+0

也感谢其他帮手。我标记了最明确的解释。 – 2015-02-12 08:52:32