我試圖運行該程序時,出現IndexError:list assignment index超出範圍錯誤。我的索引看起來很好(從0到8),我不認爲.append是需要的,因爲等號每次傳遞隨機值。我錯過了什麼?在python中生成隨機整數列表3
import random
#The main function.
def main():
#Welcome message.
print("Welcome to the lottery number generator program!")
print()
#Explain what the program does.
print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
print("________________________________________________________________________________________________")
print()
print()
#Call the generateNumbers function and store its returned list in variable lotteryNumbers.
lotteryNumbers = generateNumbers()
#Call the printLottery function and pass the lotteryNumbers list as argument.
printLottery(lotteryNumbers)
#The generateNumbers function generated 7 random digits between 0 and 9 stores them in a list and returns the list.
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = []
#Declare and set loop counter to 0.
index = 0
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
index += 1
return lotteryNumbers
def printLottery(lotteryNumbers):
print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))
#End main
main()
您不能分配一個列表dinamically,你需要預先分配,如果你w螞蟻通過切片來訪問它的元素。你需要使用append – gionni
'index + = 1'不是必需的。相反: – fredtantini
:追加是需要的! – dnalow