【代码】校验身份证号码

前言

用Python校验身份证号码的正确性
通过第18位验证前17位的正确性

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
通过第18位号码校验前17位号码是否有误
"""

# 在控制台获取一组18位的身份证号
identification_number = input("请输入18位身份证号:\n")
# 声明一个空列表
array = []
# 将每一位字符放入列表
for i in identification_number:
array.append(i)
# 将前17位数字进行数据类型转换,转换为整型
for i in range(17):
array[i] = int(array[i])
# 进行乘积求和运算,系数:7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
sum = array[0]*7 + array[1]*9 + array[2]*10 + array[3]*5 + array[4]*8 + array[5]*4 + array[6]*2 + array[7]*1 + array[8]*6 + array[9]*3 + array[10]*7 + array[11]*9 + array[12]*10 + array[13]*5 + array[14]*8 + array[15]*4 + array[16]*2
# 将求和与11取余
remainder = sum%11
# 判断余数(0-10)是否与1-0-X -9-8-7-6-5-4-3-2对应
if((remainder==0 and array[17]=="1") \
or (remainder==1 and array[17]=="0") \
or (remainder==2 and array[17]=="X") \
or (remainder==3 and array[17]=="9") \
or (remainder==4 and array[17]=="8") \
or (remainder==5 and array[17]=="7") \
or (remainder==6 and array[17]=="6") \
or (remainder==7 and array[17]=="5") \
or (remainder==8 and array[17]=="4") \
or (remainder==9 and array[17]=="3") \
or (remainder==10 and array[17]=="2")):
print("校验成功")
else:
print("校验失败")

完成

参考文献

百度百科——居民身份证号码