Credit card check exercise python
for an online free online Pyhton tutorial I need to:
to write a function which checks if a given credit card number is valid.
The function check(S) should take a string S as input. First, if the
string does not follow the format "#### #### #### ####" where each # is a
digit, then it should return False. Then, if the sum of the digits is
divisible by 10 (a "checksum" method), then the procedure should return
True, else it should return False. For example, if S is the string "9384
3495 3297 0123" then although the format is correct, the digit sum is 72
so you should return False.
The following shows what I have come up with. I think my logic is correct
but don't quite understand why it is giving me the wrong value. Is there a
structural issue in my code, or am I using a method incorrectly?
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
No comments:
Post a Comment