首页 > 解决方案 > TypeError:“str”对象不能解释为整数(我使用 input() 作为字符串而不是 int)

问题描述

我在 python 中制作了一个刽子手游戏但我得到了这个错误我知道如果我使用来自输入的整数我使用 int(x) 但我只是使用输入作为字符串我不应该得到这个错误

import random
stages = [6, 5, 4, 3, 2, 1]
word_list = ['random', 'words', 'etc']
print("guess a letter")
tries = 6
word = random.choice(word_list).lower()
word_display = '_'*len(word)
print('the word is '+word)
print(f'>{word_display}')
while tries:
    choice = input('>').lower()
    print(choice)
    if choice in word and choice not in word_display:
        for i in range(word):
            if choice == word[i]:
                word_display[i].replace(choice)
    else:
        tries -= 1
        print(stages[tries])

当我给出正确的字母时,这里发生的错误是错误代码

Traceback (most recent call last):
  File "/storage/pyt/tempCodeRunnerFile.py", line 14, in <module>
    for i in range(word):
TypeError: 'str' object cannot be interpreted as an integer

标签: pythonpython-3.xstringfor-loopdebugging

解决方案


您需要传递单词的长度,因为字符串对象不能被迭代。python 中的 range() 只接受整数。尝试范围(len(word))


推荐阅读