【问题标题】:python: list index out of range error in codepython:代码中的列表索引超出范围错误
【发布时间】:2016-07-30 11:46:35
【问题描述】:

我对 python 还很陌生,而且真的很坚持。

基本上,我应该制作一个检查码来检查 NRIC 的最后一个字母。只要有 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.

【问题讨论】:

  • “以0开头的数字”是什么意思?
  • 如果链接的图像是您的实际任务,那么您没有正确执行。您需要编写一个将 NRIC 字符串作为参数的函数。你的函数不应该调用input()函数,它需要返回校验码。您发布的代码中的逻辑确实没有将支票号码正确地转换为支票代码。

标签: python


【解决方案1】:

当您将字符串输入转换为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)...")

【讨论】:

  • 代码还有另一个问题值得指出:如果有人不输入数字怎么办?如果他们输入"ZZZZZZZ" 或类似的东西怎么办? (这显然是家庭作业。)
  • @YeoZheYong 我认为这是 user268396 声明的重点。这是您可能想要做的额外级别的输入验证... :) 在尝试任何操作之前检查他们是否输入了 7 个字符并且它们都是数字...
【解决方案2】:

这是一种计算 NRIC 校验码的简洁方法。如果将无效字符串传递给函数,则会引发 ValueError 异常,这将导致程序崩溃。如果传递了非字符串类型错误,则会引发。您可以使用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

【讨论】:

    【解决方案3】:

    编辑:此代码验证输入是否由 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()
    

    【讨论】:

    • 嗯......你想要break而不是continue,否则它只会打印完成并再次循环,即使在有效输入下......另外,检查应该是@987654324 @
    【解决方案4】:

    当您强制输入为 int 时,前导 0 将被解释为 Python 3 中的错误。例如,int(0351) 不会产生 0351351,但只会导致错误声明 @ 987654324@.

    您不应强制输入为 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.")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2014-12-02
      • 2021-05-12
      • 1970-01-01
      • 2016-01-06
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多