[英]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!")
The only syntactic problem with your code is that you can't do for i in len(nameList)
, you have to use range()
if you want to loop a certain number of times. 您的代码唯一的语法问题是您无法for i in len(nameList)
做for i in len(nameList)
如果要循环一定次数,则必须使用range()
。 It will work if you change the last section to: 如果将最后一部分更改为:
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)
returns an integer you should call range(len(nameList))
instead. len(nameList)
返回一个整数,您应该改为调用range(len(nameList))
。 However, the code will be cleaner if you write it like: 但是,如果您这样编写代码,则代码将更加简洁:
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.