python:代码中的列表索引超出范围错误

时间:2016-07-30 11:46:35

标签: python

我对python很新,并且真的坚持这个。

基本上,我应该制作一个检查代码来检查身份证的最后一个字母。只要有7个数字(就像应该有的话),我的代码就能正常工作。但是,我的老师刚刚帮我发现,只要数字从0开始,我的代码就不起作用。下面是我的代码。

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)

    print(checkcode)

check_code()

这是计算NRIC的方式,如下图所示。

NRIC calculation help.

4 个答案:

答案 0 :(得分:2)

当您将字符串输入转换为int时,前导零被剥离(例如"0153444" - > 153444)。当您在列表推导中再次转换回字符串时,您将不会返回零,因此最终得到[1,5,3,4,4,4]的NRIC列表而不是[0,1 ,5,3,4,4,4]。如果您删除int这样的呼叫,则不会丢失前导零。

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

答案 1 :(得分:1)

这是一种计算NRIC检查代码的简洁方法。如果向函数传递了无效字符串,则会引发ValueError异常,这将导致程序崩溃。如果传递非字符串,则会引发TypeError。您可以使用try:... except语法捕获异常。

def check_code(nric):
    if len(nric) != 7 or not nric.isdigit():
        raise ValueError("Bad NRIC: {!r}".format(nric))

    weights = (2, 7, 6, 5, 4, 3, 2)
    n = sum(int(c) * w for c, w in zip(nric, weights))
    return "ABCDEFGHIZJ"[10 - n % 11]

# Test
nric = "9300007"
print(check_code(nric))

<强>输出

B

答案 2 :(得分:0)

编辑:此代码验证输入是否由7位数组成。

def check_code():       
    while True:

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

        if len(nricno) == 7 and nricno.digits == True:
            print ("Works")
            continue
        else:
            print("Error, 7 digit number was not inputted and/or letters and other characters were inputted.")


    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)

    print(remainder)

    leftovers = int(11 - remainder)

    rightovers = leftovers - 1 

    Alphabet = "ABCDEFGHIZJ"

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

    print(checkcode.upper())

check_code()

答案 3 :(得分:0)

当您将输入强制为int时,前导0将在Python 3中被解释为错误。例如,int(0351)不会产生0351351,但会只是导致错误陈述invalid token

你不应该强制输入为int,而是添加一个断言语句,声明输入的值必须是7位整数(或者你喜欢的常规语句)。

改变这个:

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

对此:

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