2015-03-02 10 views
-1
def total(): 
    n = prompt() 
    answer = (n-2)*180 
    print ("The polygon has", answer, "sides.") 

def prompt(): 
    x = raw_input("Type number: ") 
    return x 

我試圖讓n這等於prompt輸出是一個整數,這樣數學上就可以完成。我將如何做到這一點?的raw_input轉換器的輸出爲整數

+1

'n = int(prompt())',或者'return int(x)'(取決於你想要轉換的地方) – poke 2015-03-02 20:05:40

+0

這工作謝謝。 – 2015-03-03 18:18:06

回答

0

raw_input返回一個字符串,所以你不能用它進行任何計算。如果你想有一個整數,你可以使用int函數來轉換值。你可以做,要麼你prompt函數中,或在後面的調用函數(儘管它將使更有意義,詢問了許多回一個用戶的功能):

def prompt(): 
    x = raw_input("Type a number: ") 
    return int(x) 

注意,那int()可能對於任何用戶輸入的非有效整數值,請提出ValueError。在這種情況下,您應該捕獲異常並再次提示用戶更正輸入。有關如何工作,請參閱this question