如何修复python中的“列表索引超出范围”错误?

时间:2019-05-28 08:53:16

标签: python arrays python-3.5 sqldatatypes

我正在为考勤系统设置RFID阅读器。但是,当我将标签放置到阅读器上时,它被标签ID中断-我将标签ID外部存储到数据库中。

#//////place your tag//////

print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

(error, uid) = rdr.anticoll()
if not error:
    print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]) 

print("Written..!")
print(tagid)


cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
connection.commit()
print("Data was successfully Added...!")

tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]) 
IndexError: list index out of range

1 个答案:

答案 0 :(得分:1)

您的代码结构不正确。每当标记请求不正确时,尝试使用缩进rdr.anticoll(),将不会发生任何过程。

尝试以下代码行以获得更好的可视化效果:

print("Now place your tag to write")
rdr.wait_for_tag()

(error, data) = rdr.request()
if not error:
    print("\nDetected: " + format(data, "02x"))

    (error, uid) = rdr.anticoll()
    if not error:
        print("Card read UID: " +str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]))

        tagid = str(uid[0])+str(uid[1])+str(uid[2])+str(uid[3]) 

        print("Written..!")
        print(tagid)
        cursor.execute("insert into rfid_check (uid,firstname,age,tag_id) values ('%s','%s','%s','%s')" %(user_id,fname, ag_e, tagid))
        connection.commit()
        print("Data was successfully Added...!")
else:
    print("Unsuccessful")