返回

深入理解身份证号校验规则,用Python代码轻松实现

后端

身份证号校验是一项重要的任务,它可以帮助我们识别并防止身份欺诈。身份证号校验的规则如下:

  1. 身份证号由15位或18位数字组成,其中最后一位是校验位。
  2. 身份证号的前6位表示省、市、县、区。
  3. 身份证号的第7-14位表示出生日期,其中前2位表示年份,中间2位表示月份,后2位表示日期。
  4. 身份证号的最后一位是校验位,它是根据前17位数字计算得出的。

我们可以使用 Python 代码轻松实现身份证号校验。以下是一个简单的示例:

def is_valid_id_number(id_number):
    # Check if the length of the ID number is 15 or 18.
    if len(id_number) not in [15, 18]:
        return False

    # Check if the ID number is all digits.
    if not id_number.isdigit():
        return False

    # Check if the ID number is valid according to the Luhn algorithm.
    if not luhn_checksum(id_number):
        return False

    # Check if the ID number is valid according to the ID number rules.
    if not id_number_rules(id_number):
        return False

    return True


def luhn_checksum(id_number):
    # Calculate the checksum of the ID number.
    checksum = 0
    for i, digit in enumerate(id_number):
        digit = int(digit)
        if i % 2 == 0:
            digit *= 2
        if digit > 9:
            digit -= 9
        checksum += digit

    # Check if the checksum is valid.
    return checksum % 10 == 0


def id_number_rules(id_number):
    # Check if the ID number is valid according to the ID number rules.
    if id_number[0:2] not in ["11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82"]:
        return False
    if id_number[6:8] > "20":
        return False
    if id_number[10:12] > "31":
        return False
    if id_number[14:17] not in ["001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016", "017", "018", "019", "020"]:
        return False

    return True


if __name__ == "__main__":
    id_number = input("请输入身份证号:")
    if is_valid_id_number(id_number):
        print("身份证号有效。")
    else:
        print("身份证号无效。")

这个 Python 代码示例可以帮助您轻松实现身份证号校验。您只需要将身份证号输入到程序中,程序就会自动判断身份证号是否有效。