2013-07-14 25 views
0

我正在學習代碼學院的python,並試圖完成他們的審查任務。 我應該定義一個函數,然後設置一個if/else循環來檢查我得到的輸入的類型,然後返回int/float的絕對值或錯誤消息。如何在調用函數時修復「NameError:name'事件未定義」?

我試着看類似的問題,但我不明白這些代碼比我能理解的O_O複雜得多。我再次看了功能模塊課程,但我想我正確地遵循了功能模式?在我調用函數之前是否應該有額外的行?我試圖繼續前進,但是我在其他練習中得到了同樣的錯誤信息。

我將不勝感激任何迴應:)

def distance_from_zero(thing): 
    thing = input 
    if type(thing) != int or float: 
     return "Not an integer or float!" 
    else: 
     return abs(thing) 
distance_from_zero(thing) 
+0

你根本沒有''中distance_from_zero thing'定義(事)'。 – Rubens

+0

'input'沒有被定義。 – alecxe

+0

來定義一個變量,我不能設置等於輸入? – user1476390

回答

2

您是否嘗試使用輸入函數從用戶獲取值? 如果是這樣,你必須添加括號到它:

thing = input() 
# If you're using python 2.X, you should use raw_input instead: 
# thing = raw_input() 

此外,如果這是你想做什麼,你不需要輸入參數。

如果您的意思是input是一個參數,那麼您在定義它們之前嘗試使用變量。因爲thingdistance_from_zero(thing)不能工作尚未你的函數定義之外,所以您應該定義變量或先用litteral值稱之爲:

thing = 42 
distance_from_zero(thing) 
# or 
distance_from_zero(42) 
+0

我明白了錯誤信息,感謝你的解釋=) – user1476390

1

你不定義thing。請嘗試

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

thing = 1 
distance_from_zero(thing) 

或者您的意思是這個,接受用戶輸入?

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

您的代碼if type(thing) != int or float:會經常去True它是if (type(thing) != int) or float。將其更改爲if not isinstance(thing, (int, float)):

1

thing當您將它傳遞給distance_from_zero函數時未定義?

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

thing = 5 
distance_from_zero(thing) 
相關問題