简体   繁体   English

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

[英]How to fix 'list index out of range' error in python?

I'm setting up the RFID reader for the attendance system. 我正在为考勤系统设置RFID阅读器。 But when I place my tag to the reader, it was interrupted with the Tag id - which I externally stored to a database. 但是,当我将标签放置到阅读器上时,它被标签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

Your code structure is not correct. 您的代码结构不正确。 Try to indent rdr.anticoll() with this whenever the tag request is incorrect no process will occur. 每当标记请求不正确时,尝试使用缩进rdr.anticoll(),将不会发生任何过程。

Try the line of codes for better visualization: 尝试以下代码行以获得更好的可视化效果:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM