我對python非常陌生,並且真的停留在此。python:代碼中的列表索引超出範圍錯誤
基本上,我應該做一個檢查代碼來檢查NRIC的最後一個字母。只要有7個數字(比如應該有的),我的代碼就可以正常工作。然而,我的老師只是幫助我發現,只要數字以0開頭,我的代碼就無法工作。下面是我的代碼。
def check_code():
nricno = int(input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will fail."))
NRIC = [ int(x) for x in str(nricno) ]
a = NRIC[0]*2
b = NRIC[1]*7
c = NRIC[2]*6
d = NRIC[3]*5
e = NRIC[4]*4
f = NRIC[5]*3
g = NRIC[6]*2
SUM = int(a + b + c + d + e + f +g)
remainder = int(SUM % 11)
leftovers = int(11 - remainder)
rightovers = leftovers - 1
Alphabet = "ABCDEFGHIZJ"
checkcode = chr(ord('a') + rightovers)
print(checkcode)
check_code()
這是在下圖中應該計算NRIC的方式。
什麼是 '一個數字,從0開始' 的意思嗎? – Julien
如果鏈接的圖像是你的實際任務,那麼你做得不好。您需要編寫一個將NRIC字符串作爲參數的函數。你的函數不應該調用'input()'函數,它需要返回校驗碼。您發佈的代碼中的邏輯確實_not_將檢查號碼正確轉換爲檢查代碼。 –