python输入一个身份证号码,判断其是否有效: 若不为18位,提示“长度错误”; 若前17位存在非数字,提示“存在无效字符”; 最后一位为校验码,若错误,提示“校验码错误”, 若正确,提示“校验码正确”。
时间: 2024-06-11 12:08:03 浏览: 14
id_card = input("请输入身份证号码:")
if len(id_card) != 18:
print("长度错误")
else:
if not id_card[:17].isdigit():
print("存在无效字符")
else:
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
total = 0
for i in range(17):
total += int(id_card[i]) * weights[i]
if check_codes[total % 11] != id_card[-1].upper():
print("校验码错误")
else:
print("校验码正确")