当前位置: 代码迷 >> python >> 我对字符串和整数有些困惑,并且不断收到此错误:TypeError:列表索引必须是整数或切片,而不是str
  详细解决方案

我对字符串和整数有些困惑,并且不断收到此错误:TypeError:列表索引必须是整数或切片,而不是str

热度:30   发布时间:2023-06-13 17:01:25.0
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)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!")

len(nameList)返回一个整数,您应该改为调用range(len(nameList)) 但是,如果您这样编写代码,则代码将更加简洁:

print("You may invite up to six people to your party.")

name_list = []
for current_name in range(6):
    name = input("Enter invitee's name (or just press enter to finish): ")
    if not name:
        break
    name_list.append(name)

for invitee in name_list:
    print(invitee + ", please attend our party this Saturday!")
  相关解决方案