2017年9月23日 星期六

[Python] 檢查台灣身份證號碼

最近學習 python,實作書本上的題目,其中一個練習是檢查所輸入的身份正證號碼是否正
確。

台灣身份證的編碼規則,請參考該網址說明。

實作概念:
1. 透過 Dictionary 建立身分證第一碼(地區碼)的對應表:對應表內容皆由 List 產生,透過 zip() 將英文和數字編碼合併在一起,而建立出地區碼對應表
2. 偵測明顯的錯誤(如:長度錯誤,第一碼非英文字元...等)
3. 將輸入的身份證內容取出,並根據身份證編碼規則,將輸入內容轉換成 check sum
4. 檢查 check sum 是否符合身分證編碼規則

程式碼:

import string

# create alphabet for 1st char of ID
alphabet = list(string.ascii_uppercase[0:8])
alphabet.extend(list(string.ascii_uppercase[9:]))
code = list(range(10,33))

# create the location mapping code for char of ID
locationCode = dict(zip(alphabet,code))

while(1):
    id = input('Please input your security id: ')
    if id == 'exit':
        break
    elif len(id) != 10 or not(id[0].isalpha()) \
            or not(id[1:].isdigit() or int[id[1] > 2 or id[1] < 1]):
        print('Error: wrong format')
        continue
    # Convert 1st Alphabet to Numeric code
    encodeID = list(str(locationCode[id[0].upper()]))
    encodeID.extend(list(id[1:]))
    print(encodeID)
    checkSum = int(encodeID[0])

    # Calculate the checksum of ID
    para = 9
    for n in encodeID[1:]:
        if para == 0:
            para = 1
        print(n, para)
        checkSum += int(n)*para
        para -= 1

    # Check the checksum
    if checkSum % 10 == 0:
        print("ID is correct")
    else:
        print('Error: ID is not correct')

沒有留言:

張貼留言