[英]Assigning to list in while loop for python 3
我有以下一些python代码:
# we are going to define a list:
charList = []
#which we can use to add character's data to
i = 0
print("Please input data for your first character below: ")
while i <= 5:
charList[i] = input("What is their name? ")
i += 1 # increments i by 1
charList[i] = input("\nAnd what is their strength value? ")
i += 1
charList[i] = input("\nAnd what is their skill value? ")
i += 1
print("\nThank You :)\n")
print("Now for your second character:")
print(charList[0],charList[3])
这适用于3.4.0版。
它出现以下错误:
>>>
Please input data for your first character below:
What is their name? Chewbacca
Traceback (most recent call last):
File "C:/Users/Peter/Documents/ARCHIVES/NEW!/Computing/task3version1.0.py", line 20, in <module>
charList[i] = input("What is their name? ")
IndexError: list assignment index out of range
>>>
我猜这是在while循环中改变i值的问题。 关于什么是错的任何想法? 谢谢 :)
访问列表的索引(如charList[i]
中)可以访问/操作列表的现有元素。 由于charList
从空开始,因此没有可访问的元素。 正如您所见,尝试这样做会给您带来超出范围的错误。
相反,你似乎想要附加到列表,如下所示:
charList.append(input("What is their name? "))
你为什么要在一个周期中做这件事? 你试图重写相同的列表5次。
questions = ("What is their name? ", "\nAnd what is their strength value? ", "\nAnd what is their skill value? ")
print("Please input data for your first character below: ")
charlist = [input(i) for i in questions]
print("\nThank You :)\n")
print(charList[0],charList[3])
如果你想要几个字符:
charlist = []
questions = ("What is their name? ", "\nAnd what is their strength value? ", "\nAnd what is their skill value? ")
print("Please input data for your first character below: ")
for i in range(5):
character = [input(i) for i in questions]
charlist.append(character)
print("\nThank You :)\n")
print(charList[0][0],charList[3][0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.