我正在尝试创建一个简单的数组程序并打印出数组元素但在输入employee 2值之后立即收到错误:IndexError:list assignment index超出范围。
#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])
答案 0 :(得分: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]
答案 1 :(得分: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中,您不能使用相同的语法。祝你好运。