python - 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
解决方案
您需要传递单词的长度,因为字符串对象不能被迭代。python 中的 range() 只接受整数。尝试范围(len(word))
推荐阅读
- gitlab - 将 docker 映像推送到 gitlab 的(本地)集成 docker 注册表时访问被拒绝
- javascript - 在尝试了这个例子之后,对 JavaScript 中的 Maps 和 Set 的基础感到困惑
- typescript - 如何设置订阅状态是否已完成或错误的常见行为?
- mongodb - MongoDB 使用聚合执行连接
- python - 在 SpaCy 的优化器中更改默认学习率
- spring-cloud - 如何使用 URL->responsible-backend-service 映射服务动态路由传入请求?
- r - 如何使用 3 个输入变量在 R 中绘制线性判别分析图的决策边界
- linux - 随机读/写一个大文件-每次读/写时都使用mmap?
- scala - 如何在运行时为 docker 容器提供端口号?
- office365 - 在office365中调用create user时一个或多个属性包含无效值