2016-03-24 66 views
0

我正在做一個hang子手。這裏是我的代碼:Python hang子手錯誤

from random import choice 


word = choice(["gpu", "cpu","motherboard","alu","cache","ram","hardware","hosted software","monitor","keyboard"]) 
word_len = len(word) 
guessed = [] 
wrong = 6 
space = word.find(" ")!=-1 
while True and wrong > 0: 
    out = "" 
    if space == True: #somewords have a space so i did this to 
     guessed =" " #put the space in there and reduce the length by one 
     word_len -=1 # it works fine without this. 
    for letter in word: 
     if letter in guessed: 
      out = out + letter 
     else: 
      out = out + "_" 
    if out == word: 
     print("You guessed", word) 
     break 
    print("Guess the ", word_len, "letter word:", out) 
    guess = input() 
    if guess in guessed: 
     print("Already guessed", guess) 
    elif guess in word: 
     print("Yay") 
     guessed.append(guess) 
    else: 
     print("Nope") 
     wrong = wrong - 1 
     print("You have ", wrong," attempts left.") 
     if wrong == 0: 
      print ("You lost. The word was ",word) 
    print() 

讀3行# 錯誤代碼,我得到當我運行是這樣的:

Traceback (most recent call last): 
    File "C:\Users\Alex\Documents\codes\hangman.py", line 28, in <module> 
    guessed.append(guess) 
AttributeError: 'str' object has no attribute 'append' 

正如我所說的,它工作正常,而不該代碼與#下一到它,但我需要的代碼。沒有任何人有任何想法

+0

你改變了類型,當你這樣做...... guessed =「」#輸入空間在那裏,並減少一個 – clutton

+0

在條件'if space == True'你重新分配'猜測'沒有'list'這樣的沒有方法'append'的str'類型的值。 – woozyking

回答

2

您轉換guessed成字符串在這一行:

guessed =" " #put the space in there and reduce the length by one 

離開它作爲一個列表,如果你想追加到它。

+0

打我吧!但是,這就是你的問題所在。 – Firearrow5235