python:代码中的列表索引超出范围错误
我对python还很陌生,而且在这方面我真的很在行 基本上,我应该做一个检查代码来检查NRIC的最后一个字母表。只要有7个数字(就像应该有的那样),我的代码就可以正常工作。然而,我的老师只是帮我发现,只要数字以0开头,我的代码就不起作用。下面是我的代码python:代码中的列表索引超出范围错误,python,Python,我对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
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的计算方法,如下图所示
当您将字符串输入转换为
int
时,前导零将被去除(例如“0153444”
->153444
)。当您在列表理解中再次转换回字符串时,您将无法返回零,因此最终得到的NRIC列表为[1,5,3,4,4,4],而不是[0,1,5,3,4,4]。如果像这样删除int
调用,则不会丢失前导零
# Change this:
nricno = int(input("Please enter your NRIC(numbers only)..."))
# To this:
nricno = input("Please enter your NRIC(numbers only)...")
编辑:此代码验证输入是否由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()
这里有一个计算NRIC校验码的简洁方法。如果将无效字符串传递给函数,将引发ValueError异常,这将导致程序崩溃。如果传递了非字符串,则将引发TypeError。您可以使用
try:。。。语法除外
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
在Python3中,强制输入为int时,前导0将被解释为错误。例如,int(0351)
既不会产生0351
也不会产生351
,只会导致一个声明无效令牌的错误
您不应该强制输入为int,而是应该添加一个断言语句,声明输入的值必须是7位整数(如果愿意,也可以添加一个常规语句)
更改此项:
nricno=int(输入(“请输入您的NRIC(仅限数字)。如果您不键入NRIC号码,此代码将失败”)
为此:
nricno=input(“请输入您的NRIC(仅限数字)。如果您不键入NRIC数字,此代码将失败。”)
以0开头的数字是什么意思?如果链接图像是您的实际分配,则说明您没有正确执行。您需要编写一个将NRIC字符串作为参数的函数。您的函数不应该调用input()
函数,它需要返回检查代码。您发布的代码中的逻辑没有正确地将支票号码转换为支票代码。代码中还有另一个值得指出的问题:如果有人没有键入数字怎么办?如果他们键入“zzzzz”
或类似的内容会怎么样?(这显然是家庭作业。)@Yeozheong我想这就是user268396声明的重点。这是您可能希望执行的输入验证的附加级别…:)在尝试任何操作之前,请检查他们是否输入了7个字符,并且所有字符都是数字,例如…嗯。。。你需要的是break
而不是continue
,否则即使在有效输入的情况下,它也只能打印完成并再次循环。。。此外,如果len(nricno)==7且nricno.isdigit(),则检查应为