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:列表索引必须是整数或切片,而不是str,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33323825/

10-12 16:03