类型错误:整数类型的参数不可迭代?
我正在尝试用Python 2.7写一个猜单词游戏(也叫“吊死鬼”),但是在代码中有一行出现了类型错误,那一行是:
print char.
抱歉,我忘了加上其余的代码。下面是完整的代码。这个单词是从一个字典文件中获取的。
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
wordlist = load_words()
print "Welcome to Hangman where your wits will be tested!"
name = raw_input("Input your name: ")
print ("Alright, " + name + ", allow me to put you in your place.")
word = random.choice(wordlist)
print ("My word has ")
print len(word)
print ("letters in it.")
guesses = 10
failed = 0
for char in word:
if char in guesses:
print char,
else:
print "_",
failed += 1
if failed == 0:
print "You've Won. Good job!"
break
#
guess = raw_input("Alright," + name + ", hit me with your best guess.")
guesses += guess
if guess not in word:
guesses -= 1
print ("Wrong! I'm doubting your intelligence here," + name)
print ("Now, there's only " + guesses + " guesses left until the game ends.")
if guesses == 0:
print ("I win! I win! I hanged " + name + "!!!")
1 个回答
1
你尝试:
if char in guesses:
不过,guesses
只是剩余猜测次数的 计数,是一个整数,所以你不能对它进行循环操作。也许你应该把之前的猜测也存起来,然后使用这些:
guess_list = []
...
if char in guess_list:
...
guess_list.append(guess)
出于同样的原因,如果你走到了这一步,
guesses += guess
会失败 - guess
是一个字符串,而 guesses
是一个整数,这两者是不能直接相加的。