Skip to content

Instantly share code, notes, and snippets.

@iEverX
Created August 23, 2012 07:43
Show Gist options
  • Save iEverX/3433900 to your computer and use it in GitHub Desktop.
Save iEverX/3433900 to your computer and use it in GitHub Desktop.
身份证校验码计算
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import reduce
# 系数,fix = (2 ** (17 - i) % 11 for i in range(17))
fix = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
# 根据身份证号前17位计算第18位
def get_check_code(id_head):
if len(id_head) != 17:
return -1
if not id_head.isdigit():
return -1
_sum = reduce(lambda x, y: x + y[0] * int(y[1]), zip(fix, id_head), 0)
_result = 12 - _sum % 11
return _result - 11 if _result > 10 else _result
# 判断输入的身份证号是否为合法的身份证号
def check_id(id_num):
if len(id_num) != 18:
return False
if id_num[:17].isdigit():
check_code = get_check_code(id_num[:17])
else:
return False
if check_code == 10 and id_num[17] == 'X' or (
check_code == int(id_num[17])):
return True
return False
if __name__ == '__main__':
while True:
input_id = input().strip()
if input_id == '00':
break
print(check_id(input_id), get_check_code(input_id[:17]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment