2012-03-18 84 views
0
# Let's create a file and write it to disk. 
filename = "test.dat" 
# Let's create some data: 
done = 0 
namelist = [] 
while not done: 
    name = raw_input("Enter a name:") 
    if type(name) == type(""): 
     namelist.append(name) 
    else: 
     break 

對於上面的Python代碼,我試過了,但是無法從while循環中斷開。它總是要我「輸入名稱:」,無論我輸入什麼。 如何突破循環?如何擺脫while循環?對於Python字符串類型

+3

您從用戶接收到的輸入將始終爲字符串輸入,除非您將其轉換。 – 2012-03-18 15:33:17

+0

爲了調試這個,你可以添加一些打印語句,比如'print name,repr(name),type(name)','print type(「」)','print type(name)== type(「 )'等等,這會顯示出問題。通過分散打印聲明,你很少會出錯。 – DSM 2012-03-18 15:38:18

回答

4
# Let's create a file and write it to disk. 
filename = "test.dat" 
# Let's create some data: 
namelist = [] 
while True: 
    name = raw_input("Enter a name:") 
    if name: 
     namelist.append(name) 
    else: 
     break 

時輸入什麼

1

這打破這是因爲raw_input總是返回一個字符串,即type(name) == type("")始終是真實的。請嘗試:

while True: 
    name = raw_input("Enter a name: ") 
    if not name: 
     break 
    ... 
+0

謝謝你們兩位!該代碼是從其他人的網頁中提取的,所以它帶有錯誤! – user866735 2012-03-18 15:40:56