Yeo Zhe Yong Yeo Zhe Yong - 1 year ago 56
Python Question

python: list index out of range error in code

I'm pretty new to python, and really stuck at this.

Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number starts with 0. Below is my code.

def check_code():
nricno = int(input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will fail."))

NRIC = [ int(x) for x in str(nricno) ]

a = NRIC[0]*2
b = NRIC[1]*7
c = NRIC[2]*6
d = NRIC[3]*5
e = NRIC[4]*4
f = NRIC[5]*3
g = NRIC[6]*2

SUM = int(a + b + c + d + e + f +g)

remainder = int(SUM % 11)
leftovers = int(11 - remainder)

rightovers = leftovers - 1

Alphabet = "ABCDEFGHIZJ"

checkcode = chr(ord('a') + rightovers)



This is the way the NRIC is supposed to be calculated, in the image below.

NRIC calculation help.

Answer Source

When you convert the string input into an int, the leading zero is stripped away (e.g. "0153444" -> 153444). When you convert back to a string again in the list comprehension, you won't get the zero back, so you end up with an NRIC list of [1, 5, 3, 4, 4, 4] instead of [0, 1, 5, 3, 4, 4, 4]. If you remove the int call, like this, you won't lose the leading zero.

# Change this:
nricno = int(input("Please enter your NRIC(numbers only)..."))
# To this:
nricno = input("Please enter your NRIC(numbers only)...")