需要帮助了解Typeerror

时间:2019-06-09 01:16:09

标签: python python-3.x typeerror

我收到“ TypeError:'in'要求将字符串作为左操作数,而不是Builtin_function_or_method”,并且在检查单词中是否出现猜测的字母时,我不太了解如何解决此问题。

只需要知道执行此操作的最佳其他方法即可。

import random
wordlist = ['python','hangman','hippopotamus','eschscholtzia']
word = random.choice(wordlist)

answer = word[0:30]
display = []
display.extend(answer)
for i in range(len(answer)):
    display[i] = '_'

print('Welcome to hangman, type quit to exit program.')
print('the word has', len(word), 'letters')
print(display)
guess = input('pick a letter? ')
guess = guess.lower

for i in range(len(answer)):
    if display[i] == guess:
        display[i] = guess

while guess != 'quit':
guessedletters = []
guessedletters.append(guess)
if guess in word:
    print('Well Done it has',word.count(guess),guess)
else:
    print('sorry no',guess,'in the word')

3 个答案:

答案 0 :(得分:1)

当您使用guess = guess.lower调用.lower()时,您只是在指“ lower”方法而不是实际调用它

如果将该行更改为

guess.lower()

然后它应该解决您的问题

之所以引发异常,是因为您试图查看方法“ lower”是否在一个单词中,而不是在调用该方法时返回的字符串

答案 1 :(得分:1)

除了@ wertie8297很好地解释(+1)的guess = guess.lower问题之外,您的代码还有其他问题。例如,这段代码:

for i in range(len(answer)):
    if display[i] == guess:
        display[i] = guess

似乎什么也没做。同样,您的缩进不正确,并且您的选择字母逻辑在循环之外(之前),因此游戏将永远无法进行。这是对代码的重做,可以解决其中的一些问题并尝试制作可玩的游戏:

from random import choice

WORD_LIST = ['python', 'hangman', 'hippopotamus', 'eschscholtzia']

word = choice(WORD_LIST)

print("Welcome to hangman, type 'quit' to exit program.")
print("The word has", len(word), "letters.")

display = ['_' for _ in word]

guessed_correct_letters = set()

while True:
    print(*display)

    guess = input("pick a letter: ")
    guess = guess.lower()

    if guess == 'quit':
        break
    if guess in guessed_correct_letters:
        print("You already found", guess, "in the word")
    elif guess in word:
        guessed_correct_letters.add(guess)

        print("Well Done, it has", word.count(guess), guess)

        display = [letter if letter in guessed_correct_letters else '_' for letter in word]

        if '_' not in display:
            print("Congratulations, you solved it!")
            break
    else:
        print("Sorry, no", guess, "in the word")

答案 2 :(得分:0)

上面写着guess = guess.lower的地方。

lower()函数,不进行调用就赋予它类似<__main__:lower object at 0x12345678>

的奇怪元数据

固定代码为guess = guess.lower()