简体   繁体   English

TypeError:类型为'int'的参数是否可迭代?

[英]TypeError: argument of type 'int' is not iterable?

I am trying to do a hangman code in python 2.7 and I'm getting the type error around the line that says 我正在尝试在python 2.7中执行a子手代码,并且在输入以下内容时遇到类型错误

print char. 打印字符。

I'm sorry, I forgot to add the rest of the code. 抱歉,我忘记添加其余代码。 Here's the full code. 这是完整的代码。 Word is coming from a dictionary file. Word来自词典文件。

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 + "!!!")

You try: 你试试:

if char in guesses: 

However, guesses is just the count of the number of guesses left, an integer, so you can't iterate over it. 但是, guesses只是剩余的猜测数量的计数 ,是整数,因此您无法对其进行迭代。 Perhaps you should also store the previous guesses and use that: 也许您还应该存储先前的猜测并使用:

guess_list = []
...
if char in guess_list:
...
guess_list.append(guess)

For the same reason, if you got that far 出于同样的原因,如果你走了那么远

guesses += guess

would fail - guess is a string and guesses an integer, which can't be added together. 会失败- guess是一个字符串,而guesses一个整数,不能将其加在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM