2017-07-22 50 views
-1

我想創建一個簡單的數組程序並打印出數組元素,但在我輸入員工2的值後說:IndexError:list assignment index out of range。列表分配索引超出範圍錯誤

#Create constant for the number of employees. 
SIZE = 3 

#Create an array to hol the number of hours worked by each employee. 
hours = [SIZE] 

#Get the hours worked by employee 1. 
hours[0] = int(input("Enter the hours worked by employee 1: ")) 

#Get the hours worked by employee 2. 
hours[1] = int(input("Enter the hours worked by employee 2: ")) 

#Get the hours worked by employee 3. 
hours[2] = int(input("Enter the hours worked by employee 3: ")) 

#Display the values entered. 
print("The hours you entered are:") 
print(hours[0]) 
print(hours[1]) 
print(hours[2]) 
+1

你沒有設置任何尺寸的小時= [SIZE],你的列表只有一個索引 – PRMoureu

+0

'[SIZE]'是一個1元素的列表,其唯一的元素是3號。 – user2357112

回答

0

值Python沒有字面數組:它有名單。 hours = [SIZE]不會創建包含3個元素的列表:它會創建一個包含1個元素的列表。您應該使用append()將項目添加到列表中,而不是索引超過數組末尾。

正確的代碼看起來像這樣的元素添加到列表:

hours.append(int(input("Enter the hours worked by employee 1: "))) 
hours.append(int(input("Enter the hours worked by employee 2: "))) 
hours.append(int(input("Enter the hours worked by employee 3: "))) 

從評論,似乎你正在學習從僞教科書代碼:這是美妙的。請記住,雖然某些常用於僞代碼的慣例,或者有時類似於C語言的慣例在其他編程語言中可能會有所不同。例如,在C中,這聲明瞭一個名爲x的50個字符的數組。

char x[50]; 

在Python中,不能使用相同的語法。祝你好運。

+1

謝謝。我正在學習編程邏輯,他們使用僞代碼,我正在嘗試將其轉換爲Python代碼。 – Cornel

+1

Python實際上的確擁有數組https://docs.python.org/3/library/array.html –

+0

@ cricket_007是的,我知道,NumPy的確是基於它們的。但不是文字數組。我應該提到這一點。謝謝。 –

0

您似乎對如何在Python中使用數組工作有錯誤的想法。本質上講,當你鍵入

#Create constant for the number of employees. 
SIZE = 3 

#Create an array to hol the number of hours worked by each employee. 
hours = [SIZE] 

你在做什麼是創建一個元素的數組的3

hours = [3] 
相關問題