2016-11-21 45 views
0

我正在編寫Python代碼,它計數到用戶提供的數字,但運行代碼時會進入無限循環。請注意我嘗試了註釋第3行和第4行,並用一個數字替換了「userChoice」,比如說5,並且它工作正常。用戶輸入的python中的無限循環

import time 

print "So what number do you want me to count up to?" 
userChoice = raw_input("> ") 

i = 0 
numbers = [] 

while i < userChoice: 
    print "At the top i is %d" % i 
    numbers.append(i) 

    i = i + 1 
    print "Numbers now: ", numbers 
    print "At the bottom i is %d" % i 
    time.sleep(1) 

print "The numbers: " 

for num in numbers: 
    print num 
    time.sleep(1) 
+0

那麼,有沒有,我很想念代碼? –

+0

導致錯誤的輸入是什麼,並且當錯誤發生時您能提供輸出樣本嗎? – SpencerD

+0

如果我選擇任何數字,代碼將無限期地打印+1號 –

回答

2

raw_input返回一個字符串,而不是int。您可以通過將用戶響應解決問題int

userChoice = int(raw_input("> ")) 

在Python不同類型的2.x的對象是compared by the type name,這樣解釋說,既然'int' < 'string'原來的行爲:

CPython的實現細節:對象除數字以外的其他類型按其類型名稱排序;不支持正確比較的相同類型的對象按其地址排序。

+0

非常感謝! –

1

您正在用字符串比較的數字:

while i < userChoice: 

字符串永遠比數量。至少在Python 2中,這些是可比的。

您需要打開userChoice成數:

userChoice = int(raw_input("> ")) 
+0

非常感謝你丹!下次我將不得不關注python變量類型。 –