I cannot figure why when I run my code I get an IndexError saying my list is out of range. I run into the error at “ if x[1] == "strongly agree": “. I’ve went through my code many times and I don’t know how to fix..
Here is my code(not including import):
firstList = [0, 0, 0, 0, 0]
secondList = [0, 0, 0, 0, 0]
with open("surveyData.txt", 'r') as f:
answers = f.read().split('\n')
for x in answers:
x = x.split(',')
if x[0] == "very happy":
firstList[0] += 1
elif x[0] == "happy":
firstList[1] += 1
elif x[0] == "neutral":
firstList[2] += 1
elif x[0] == "unhappy":
firstList[3] += 1
else:
firstList[4] += 1
if x[1] == "strongly agree":
secondList[0] += 1
elif x[1] == "agree":
secondList[1] += 1
elif x[1] == "neutral":
secondList[2] += 1
elif x[1] == "disagree":
secondList[3] += 1
else:
secondList[4] += 1
def showHistogram(dataList, bars):
plt.bars(bars, dataList)
plt.show()
question1_freq = ['very happy', ' happy', 'neutral', 'unhappy', 'very unhappy']
showHistogram(firstList, question1_freq)
question2_freq = ['strongly agree', 'agree', 'neutral', 'disagree', 'strongly disagree']
showHistogram(secondList, question2_freq)
Sample text file: unhappy,strongly agree
very unhappy,strongly agree
happy,agree
neutral,strongly agree
happy,agree
very unhappy,strongly agree
neutral,strongly agree
very happy,disagree
Just change the below line and rest seems ok
answers = f.read().splitlines()