【英文】校验身份证号码

Preface

Validating the correctness of Chinese ID card numbers using Python.
Validating the correctness of the first 17 digits using the 18th digit.

Source Code

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
"""
Validating the first 17 digits of an ID card number using the 18th digit.
"""

# Get a group of 18-digit ID card numbers from the console
identification_number = input("Please enter an 18-digit ID card number: \n")
# Declare an empty list
array = []
# Put each character into the list
for i in identification_number:
array.append(i)
# Convert the first 17 digits to integers
for i in range(17):
array[i] = int(array[i])
# Perform multiplication and sum operation with the coefficients: 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
# Take the remainder of the sum divided by 11
remainder = sum%11
# Check if the remainder (0-10) corresponds to 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("Validation successful")
else:
print("Validation failed")

Completion

References

Baidu Baike - Chinese Resident ID Card Number