2014-12-06 113 views
1

我不相信我把它設置正確......因爲不管我爲foo()填寫什麼數字,它似乎總是返回「True」。我究竟做錯了什麼??Python Return True或False

# 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))  
+0

讓我問你,你會輸入什麼來返回假 – 2014-12-06 08:55:07

+0

是的,它在我的實際程序中是正確的,但我沒有在這裏設置正確的發佈。 – 2014-12-06 08:55:45

+0

[嗯,它工作正常](http://labs.codecademy.com/CdIh#:workspace) – 2014-12-06 08:57:30

回答

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中得到整數除法,你必須使用//而不是/

+0

這對我來說是一個新聞!!!!!!!!! Thanx很多 – vks 2014-12-06 09:04:59

+1

呃...這些不同的版本正在殺死我......(沮喪) – 2014-12-06 09:05:01

+1

@ vks,你非常歡迎。 :) – merlin2011 2014-12-06 09:06:24