|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
身份证有效性校验。一个合法的中国居民身份证号码有18位,其中前6位为地区编号,第7-14位为出生日期,第15-17位为登记流水号,其中第17位是偶数为女性,是奇数则为男性,第18位为校验码。校验码的生成规则请见后面的备注。
请设计编写程序,输入18位身份证,判断其合法性,此程序我们判断两个方面的合法性,
一是长度是否是18位,并且前17位均为数字,如果不合法请给出相应提示;
二是判断最后一位校验码是否正确(注意处理字母大小写的问题),如果不合法请给出相应提示;不判断地区、生日的合法性。
如果输入的身份证非法,请用户重新输入,若输入3次仍为非法的身份证号,则结束程序,输出“输入的身份证号无法识别”。如果身份证有效,判断持有人的性别,并输出“身份证有效,持有人的性别为XX”,程序结束。能用函数实现的最好多写函数。
提示:可定义两个元组 factor、last。
factor= (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2)
last=(“1”,”0”,”x”,”9”,”8”,”7”,”6”,”5”,”4”,”3”,”2”)
备注:身份证的校验码生成规则:
将身份证17位本体码各位数字乘以对应加权因子并求和,除以11得到余数,根据余数通过校验码对照表查得校验码。
万分感谢!!!
你好,时间仓促,没有特别测试。
有问题欢迎追问
- '''中国居民身份证号码合法性检验'''
- def length_check(numbers):
- if len(numbers) == 18:
- return True
- else:
- return False
- def factors_check(factors):
- return ''.join(factors).isdigit()
- def checkcode_check(factors, last):
- sum = int(factors[0]) * 7 + int(factors[1]) * 9 + int(factors[2]) * 10 + int(factors[3]) * 5 + \
- int(factors[4]) * 8 + int(factors[5]) * 4 + int(factors[6]) * 2 + int(factors[7]) * 1 + \
- int(factors[8]) * 6 + int(factors[9]) * 3 + int(factors[10]) * 7 + int(factors[11]) * 9 + \
- int(factors[12]) * 10 + int(factors[13]) * 5 + int(factors[14]) * 8 + int(factors[15]) * 4 + \
- int(factors[16]) * 2
- right = sum % 11
- if last == 'X' or last == 'x':
- if right == 2:
- return True
- else:
- return False
- else:
- if right == int(last):
- return True
- else:
- return False
- def output(ID_numbers):
- if int(ID_numbers[16]) % 2 == 0:
- gender = "女"
- else:
- gender = "男"
- print("身份证有效,持有人的性别为" + gender)
- def legal_check():
- times = 0
- legality_flag = True
- while times < 3:
- legality_flag = True # True represents that it is legal.
- times += 1
- ID_numbers = input("请输入您的18位身份证号: ")
- ID_numbers = list(ID_numbers)
- factors = ID_numbers[:-1]
- last = ID_numbers[-1]
- # check whether the length is 18 digits
- if not length_check(ID_numbers):
- legality_flag = False
- print("输入的号码总长度不为18.")
- continue
- # check whether the factors are all numbers
- if not factors_check(factors):
- legality_flag = False
- print("前17位不全是数字。")
- continue
- # check whether the last check code is read correctly
- if (last != 'X' and last != 'x') and not last.isdigit():
- legality_flag = False
- print("最后一位应为数字,或'X'、'x'.")
- continue
- # check the legality of the checkcode
- if not checkcode_check(factors, last):
- legality_flag = False
- print("最后一位校验码不正确")
- continue
- if legality_flag:
- output(ID_numbers)
- break
- if not legality_flag:
- print("输入的身份证号无法识别")
- legal_check()
复制代码
|
|