为什么n不是整数?

时间:2016-01-07 09:43:17

标签: list typeerror

months=["Jan","Feb","March","April"]
temp =[]

for n in months:
    temp = int(input("please enter a number for ",months[n]))

这会出错:

  

TypeError:list indices必须是整数,而不是str

我不明白这一点。请帮忙。

2 个答案:

答案 0 :(得分:2)

您正在迭代字符串列表months,因此n已经是一个字符串。在for循环的每次迭代中,n等于months中的下一个项目。

months=["Jan","Feb","March","April"]
temp =[]

for month in months:
    temp.append(int(input("please enter a number for " + month)))

答案 1 :(得分:0)

 @AlanRobinson upto my knowledge it should not be  



temp = int(input("please enter a number for ",month)) 
as you r trying to type cast an array of type string to int but in unmanered way