gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:19:16 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com