簡體   English   中英

TypeError:類型為'int'的參數是否可迭代?

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

我正在嘗試在python 2.7中執行a子手代碼,並且在輸入以下內容時遇到類型錯誤

打印字符。

抱歉,我忘記添加其余代碼。 這是完整的代碼。 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 + "!!!")

你試試:

if char in guesses: 

但是, guesses只是剩余的猜測數量的計數 ,是整數,因此您無法對其進行迭代。 也許您還應該存儲先前的猜測並使用:

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

出於同樣的原因,如果你走了那么遠

guesses += guess

會失敗- guess是一個字符串,而guesses一個整數,不能將其加在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM