Python函数返回不正确的结果

时间:2015-11-12 01:22:39

标签: python function

我是Python新手编程的新手,所以如果这是一个非常基本的问题我很抱歉。出于某种原因,当我编译以下代码并运行函数pythagorean(2,3)时,我收到错误:

Error: Both a and b need to be positive

我有以下代码:

import math
def pythagorean(a, b):
    if a or b < 0:
        print("Error: Both a and b need to be positive")
    else:
        sum = math.pow(a, 2) + math.pow(b, 2)
        c = math.sqrt(sum)
        return c

根据我的理解,该程序应该跳过该条件并且不会将错误打印到屏幕上,因为a和b都大于0 ...对吗?

2 个答案:

答案 0 :(得分:1)

你应该改变

if a or b < 0:

if a < 0 or b < 0:

答案 1 :(得分:0)

尝试输入:

bool(a)

如果a是负数,或者是0,那么它将为假。否则,这将是真的。我们来看看你的代码:

if a or b < 0:

真的......

if a:
if b < 0:

由于a几乎总是如此,只需将语句更改为...

if a < 0 and b < 0:
    # do something!
相关问题