簡體   English   中英

我對字符串和整數有些困惑,並且不斷收到此錯誤:TypeError:列表索引必須是整數或切片,而不是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM