2016-07-17 79 views
1

我正在編寫一些代碼來玩Hangman(Python 3.5.2)。我不想讓自己的代碼永遠運行,例如while 1 < 2:,但是我開始在沒有while的情況下正常運行的語句上出現語法錯誤。這裏是我的代碼:將while循環添加到腳本會導致輸入錯誤

with open('dictionary.txt') as f: 
    words = f.read().splitlines() 
alphabet = 'abcdefghijklmnopqrstuvwxyz' 
words2 = '' 
alphabetCount = [] 
guesses = [] 
input = input('Input: ') 
for x in range(0, len(words)): 
    valid = True 
    if len(input) == len(words[x]): 
    for y in range(-1, len(input)-1): 
     if input[y] != words[x][y] and input[y] != '_': 
     valid = False 
    if valid: 
     words2 = words2 + (words[x]) 
for x in range(0, 26): 
    alphabetCount.append(0) 
for x in range(0, len(words2)): 
    alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1 
for z in range(0, 26): 
    if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input: 
    guesses.append(alphabet[alphabetCount.index(max(alphabetCount))]) 
    alphabetCount[alphabetCount.index(max(alphabetCount))] = 0 
print (guesses) 

從本質上講,我想循環是這樣的:

while 1 < 2: 
    with open('dictionary.txt') as f: 
    words = f.read().splitlines() 
    alphabet = 'abcdefghijklmnopqrstuvwxyz' 
    words2 = '' 
    alphabetCount = [] 
    guesses = [] 
    input = input('Input: ') 
    for x in range(0, len(words)): 
    valid = True 
    if len(input) == len(words[x]): 
     for y in range(-1, len(input)-1): 
     if input[y] != words[x][y] and input[y] != '_': 
      valid = False 
     if valid: 
     words2 = words2 + (words[x]) 
    for x in range(0, 26): 
    alphabetCount.append(0) 
    for x in range(0, len(words2)): 
    alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1 
    for z in range(0, 26): 
    if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input: 
     guesses.append(alphabet[alphabetCount.index(max(alphabetCount))]) 
    alphabetCount[alphabetCount.index(max(alphabetCount))] = 0 
    print (guesses) 
+0

無法重現。沒有語法錯誤。 –

+0

您是否驗證過您沒有混合製表符和空格? –

回答

1

出現該問題,因爲你掩蓋內置功能input()與分配:

input = input('Input: ') 

對於一次迭代,這將工作得很好,因爲你不再調用input()。不止一次執行此操作,將使用值爲input的值,在您的情況下,值爲str;調用str值將導致TypeError

將名稱更改爲不同的東西,如:

my_input = input('Input: ') 

的錯誤離開,一定要改變它在你的代碼。

請記住不要將用戶定義的名稱與built-in function names混合在一起,因爲您會收到奇怪的行爲。