簡體   English   中英

為python 3分配while循環中的列表

[英]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.

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