对于免费的在线 Python 教程,我需要:
编写一个函数来检查给定的信用卡号是否有效。该函数
check(S)
应将字符串S
作为输入。首先,如果字符串不遵循"#### #### #### ####"
每个#
数字的格式,那么它应该返回False
.10
然后,如果数字的总和可被(“校验和”方法)整除,则该过程应返回True
,否则应返回False
。例如,如果S
是字符串,"9384 3495 3297 0123"
那么虽然格式正确,但数字总和是72
,所以你应该返回False
。
以下显示了我的想法。我认为我的逻辑是正确的,但不太明白为什么它给了我错误的价值。我的代码中是否存在结构性问题,或者我使用的方法不正确?
def check(S):
if len(S) != 19 and S[4] != '' and S[9] != '' and S[14] != '':
return False # checking if the format is correct
S = S.replace(" ",'') # Taking away spaces in the string
if not S.isdigit():
return False # checking that the string has only numbers
L = []
for i in S:
i = int(i) # Making a list out of the string and converting each character to an integer so that it the list can be summed
L.append(i)
if sum(L)//10 != 0: # checking to see if the sum of the list is divisible by 10
return False