Python返回正确或错误

时间:2014-12-06 08:52:09

标签: python python-3.x

我不相信我设置正确...因为无论我为foo()填写什么数字,它似乎总是返回“True”。我做错了什么?

# Complete the following function.
# Returns True if x * y / z is odd, False otherwise.

def foo(x, y, z):
    answer = True
    product = (x * y) / z
    if (product%2) == 0:
        answer = False
    return answer

print(foo(1,2,3))    

1 个答案:

答案 0 :(得分:6)

看来OP很混乱,因为Python 3在使用/运算符时不进行整数除法。

考虑对OP程序的以下修改,以便我们更好地了解这一点。

def foo(x, y, z):
    answer = True
    product = (x * y) / z
    print(product)
    if (product%2) == 0:
        answer = False
    return answer

print(foo(1,2,3))
print(foo(2,2,2))

Python 2的输出:

python TrueMe.py 
0
False
2
False

Python 3的输出:

python3 TrueMe.py 
0.6666666666666666
True
2.0
False

毋庸置疑,输入2,2,2确实会导致生成False的返回值。

如果要在Python3中获得整数除法,则必须使用//而不是/