I'm having an issue with my code where I get the output of:
Traceback (most recent call last):
File "1stHour.py", line 48, in
ws1.cell(column=1, row=i, value="%s" % blue_student_list[i])
IndexError: list index out of range`
# coding=utf:8
from pythonzenity import Message
from openpyxl.styles import PatternFill
from openpyxl import Workbook
import bluetooth
import time
def student_check(index):
result = bluetooth.lookup_name(blue_address_list[index], timeout=3)
if (result is not None):
return True
else:
return False
blue_student_list = ['Name', 'Name2']
blue_address_list = ['Address', 'Address2']
redFill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
greenFill = PatternFill(start_color='00FF00', end_color='00FF00', fill_type='solid')
for i in range(0, len(blue_address_list)):
i = i + 1
ws1.cell(column=1, row=i, value="%s" % blue_student_list[i])
if (student_check(i)):
ws1.cell(column=2, row=i, value="%s" % "Present").fill = greenFill
else:
ws1.cell(column=2, row=i, value="%s" % "Absent").fill = redFill
Message(title="Attendance Checker",text="You can now open the Excel Document on your Desktop", timeout=3000)
I had this working but forgot to save it, so I don't have the correct way I had it before on here anymore. What can I do to prevent this error? I feel like I'm forgetting something or writing in the i = i + 1
part on my code.
When you do this:
for i in range(0, len(blue_address_list)):
there is no need to also do this:
i = i + 1
And doing so will cause the type of bug you see.
You seem to be doing this since the library you are using uses 1-based indexing rather than 0-based as in Python lists. But you are still using the (1 too high) i
to index into a list when you do this:
blue_student_list[i]
So, instead of incrementing i
a second time, pass a 1-higher value to the things that need it:
ws1.cell(column=1, row=i+1, value="%s" % blue_student_list[i])
and similarly in the other calls to ws1.cell
.
This is.. unusual for a Python library, to say the least, and so it probably warrants putting a comment like this just before you first use row=i+1
:
# Need row=i+1 because openPyXML uses 1-based indexing