python - 我对字符串和整数有点困惑,而且我一直收到此错误 : TypeError: list indices must be integers or slices, not str

标签 python python-3.x

print("You may invite up to six people to your party.")
name = input("Enter invitee's name (or just press enter to finish): ")
nameList = ["","","","","",""]
currentName = 0

while name != "":
    if currentName > 5:
        break #If more than 6 names are input, while loop ends.
    else:
        nameList[currentName] = name
        name = input("Enter invitee's name (or just press enter to finish): ")
        currentName = currentName + 1

for i in len(nameList):
    invitee = nameList[i]

    print(invitee + ", please attend our party this Saturday!")

最佳答案

你的代码唯一的语法问题是你不能做 for i in len(nameList),如果你想,你必须使用 range()循环一定次数。如果您将最后一部分更改为:

for i in range(len(nameList)): # range(5) makes a list like [0, 1, 2, 3, 4]
    invitee = nameList[i]

    print(invitee + ", please attend our party this Saturday!")

关于python - 我对字符串和整数有点困惑,而且我一直收到此错误 : TypeError: list indices must be integers or slices, not str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323825/

相关文章:

java - 如何在 Java 8 中生成给定长度的列表?

python - 如何使用密度图识别异常值

python-3.x - 如果onehotencoder应用于训练数据,如何通过测试数据来获得模型预测

python - 两个呈现的类之间有什么区别?他们的工作方式不同吗?

python - 如何让 IPython Notebook 运行 Python 3?

python - 如何加载 BeautifulSoup 页面解析器?

python - sklearn SGDClassifier 无法使其确定性地训练或预测

python - Python 命令 requests.post() 的 R 对应项是什么?

python - 运行 flask + gevent + 请求不服务 'concurrently'

python - VSCode : The Python path in your debug configuration is invalid