![](/img/trans.png)
[英]I keep getting this error: list indices must be integers or slices, not str
[英]I'm a little confused with strings and integers, and I keep getting this error: TypeError: list indices must be integers or slices, not str
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!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.