2013-04-15 30 views
-1

我一直在研究代碼,其中的一部分給了我很多麻煩。就是這個。type()函數帶整數?

import math 
number=raw_input("Enter the number you wish to find its square root: ") 
word=number 
if type(word)==type(int): 
    print sqrt(word) 

在IDLE中,無論何時輸入數字,都不會打印任何內容。我檢查了編輯器中的語法錯誤和縮進,並修復了所有這些錯誤。

+1

只是想一想:你期望'word = number'做什麼? – Matthias

回答

4

您正在尋找isinstance()

if isinstance(word, int): 

但是,這是行不通的,因爲raw_input()返回一個字符串。你也許需要異常處理,而不是:

try: 
    word = int(word) 
except ValueError: 
    print 'not a number!' 
else: 
    print sqrt(word) 

對於您的特定錯誤,type(word) is int可能還有工作,但不是很Python的。 type(int)返回int類型,這是<type 'type'>的類型:

>>> type(42) 
<type 'int'> 
>>> type(42) is int 
True 
>>> type(int) 
<type 'type'> 
>>> type(int) is type 
True 
1

的raw_input返回一個字符串。 你需要將輸入轉換爲數字

in_string = raw_input("...") 
try: 
    number = float(in_string) 
    print math.sqrt(number) 
except ValueError as e: 
    print "Sorry, {} is not a number".format(in_string)