编写程序,从键盘输入某人的身份证号,首先判断是否为一个合法的身份证号,如果是合法的身份证号,输出该人的出生日期及性别;如果不是合法的身份证号,提示用户重新输入,若输人 3 次仍为非法的身份证号,则结束输入,并输出信息“输入的身份证号无法识别!”。
为简化问题的解决,只要输入的身份证号为 18 位就认为合法,不足 18 位或超过 18 位就认为是非法。
身份证第 17 位代表性别,偶数是女,奇数是男。
失败运行效果如下:
请输入身份证号:123
请输入身份证号:123456
请输入身份证号:456
身份证号无法识别!
成功运行效果如下:
请输入身份证号:250107199912041321
出生日期:1999年12月04日
性别:女
程序源代码:
def check_id(id):
if len(id) != 18:
return False
else:
return True
def get_info(id):
year = id[6:10]
month = id[10:12]
day = id[12:14]
gender = int(id[-2]) % 2
if gender == 1:
gender = "男"
else:
gender = "女"
print("出生日期:{}年{}月{}日".format(year, month, day))
print("性别:{}".format(gender))
count = 0
while count < 3:
id = input("请输入身份证号:")
if check_id(id):
get_info(id)
break
else:
count += 1
if count == 3:
print("输入的身份证号无法识别!")
运行结果:
请输入身份证号:123
请输入身份证号:123456
请输入身份证号:456
输入的身份证号无法识别!
请输入身份证号:250107199912041321
出生日期: 1999年12月04日
性别: 女