这个比较难,主要难在考虑的问题太多,有好几个还没写出来。有空再来改进。请高手指教!
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Fan Lijun' 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") def fun(num): sum = 0 for i in range(len(num)-1): sum += (int(num[i])*Factor[i]) fina = sum % 11 if 0 <= fina <= 10: if Last[fina] == num[-1]: return num[-2] def judgement(num): if len(num) != 18: return False elif num[0] == ('0' or 'X'): return False else: return True if __name__ == '__main__': singe = 1 while singe: number = input('请输入你的身份证号码:') if judgement(number): if fun(number): s = int(fun(number)) if s % 2 == 0: sex = '女性' else: sex = '男性' print(f'这个身份证是合法身份证,性别为{sex}') singe -= 1 else: print('这个身份证不合法,请重新输入!') else: print('这个身份证不合法,请重新输入!')