2013-05-30 47 views
0

我開始用Python指南編程,但我被困在這個問題上,:Python的基礎知識(函數)

任務:

  1. 定義一個函數, 「distance_from_zero」,帶有一個參數。
  2. 具有以下功能:
    1. 檢查它接收到的輸入的類型。
    2. 如果類型爲int或float,則函數應該返回函數輸入的絕對值。
    3. 如果類型是任何其他類型,函數應該返回「不是整數或浮點數!」

我的答案(即不工作...):

def distance_from_zero(d): 
    if type(d) == int or float: 
     return abs(d) 
    else: 
     return "Not an integer or float!" 

我不知道我做錯了...謝謝你

+0

什麼是縮進?如果type(d)== int或float:'''看起來很奇怪,你應該嘗試'''如果在(int,float)中輸入(d):''''''如果isinstance(d, (int,float)):''' – oleg

+0

我改正了縮進,因爲我認爲這只是一個格式問題。 – Mene

回答

1

不能使用這種「基於自然語言的邏輯連接」。我的意思是你需要明確地陳述你的邏輯條件的部分。

if type(d) == int or type(d) == float 

這種方式,你有兩個比較,其代表自己:if type(d) == int以及type(d) == float。此結果可與or運營商結合使用。

+0

非常感謝您的回答和建議。 –

4

您應該使用isinstance而不是在這裏type

def distance_from_zero(d): 
    if isinstance(d, (int, float)): 
     return abs(d) 
    else: 
     return "Not an integer or float!" 

如果type(d) == int or float總是將是True,因爲它是爲float評價,這是一個True值:

>>> bool(float) 
True 

幫助上isinstance

>>> print isinstance.__doc__ 
isinstance(object, class-or-type-or-tuple) -> bool 

Return whether an object is an instance of a class or of a subclass thereof. 
With a type as second argument, return whether that is the object's type. 
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for 
isinstance(x, A) or isinstance(x, B) or ... (etc.). 

相關:How to compare type of an object in Python?

+0

你可以添加一些參考爲什麼'isinstance'比'type()'更好嗎? – Mene

+0

感謝您抽出寶貴時間回答,並提供'isinstance'文檔。 –

5

類型檢查應該是

if isinstance(d, int) or isinstance(d, float): 

可縮寫

if isinstance(d, (int, float)) 

什麼你當前的代碼測試是

(type(d) == int) or float 

,或者在的話:「無論是類型的dint,或float是真實的「。出於技術原因,這整個表達總是如此。編程語言中的邏輯表達式必須比自然語言更精確地指定。

+0

很好的回答和解釋。並感謝您介紹'isinstance' –

0

在編程中,如果語句不像使用簡單語言那樣工作。如果你要這樣說This fruit is an apple or an orange,你需要把它作爲

if type(fruit) == Apple or type(fruit) == Orange 

更具體的,您的問題進行編程,要使用isinstance()而不是type(),爲isinstance()將正確地考慮子類。有關更多詳細信息,請參閱this answer

所以,你應該結束了,像

def distance_from_zero(d): 
    if isinstance(d, int) or isinstance(d, float): 
     return abs(d) 
    else: 
     return "Not an integer or float!" 
+0

感謝您抽出寶貴時間回答以及'isinstance'備選方案 –

0

這是一個正確的代碼:

def distance_from_zero(d): 
     if type(d) in (int, float): 
       return abs(d) 
     else: 
       return "Not an integer or float!" 

print distance_from_zero(3) 
print distance_from_zero(-5.4) 
print distance_from_zero("abc") 

輸出:

3 
5.4 
Not an integer or float! 

請注意縮進的,在Python是與其他語言相比非常重要。

+0

感謝您的回覆,並感謝'in'替代方案 –

0

功能詳細 def distance_from_zero(d): if isinstance(d,(int,float)): return abs(d) else: return "Not an integer or float"

函數調用

print (distance_from_zero(5)) 

輸出:5

print (distance_from_zero('5')) 

輸出:不是一個整數或浮點數

0

您正在使用使得這個錯誤有太多的英文縮寫。

if type(d) == int or float: 

這意味着檢查類型是int還是float是真的......這不是你想要的。

if type(d) == int or type(d) == float: 

這將給出所需的結果。