In: Computer Science
please give complete code in python using def function thank you!
Validate Credit Card Numbers
Credit card numbers can be quickly validated by the Luhn checksum algorithm.
For instance, Ned Flander's credit card number is 8525.4941.2525.4158.
Here are the digits with checksum underlined:
8525494125254158_
Here are the digits doubled back:
16 5 4 5 8 9 8 1 4 5 4 5 8 1 10 8_
Here are the two-digit results subtracted nine:
7 5 4 5 8 9 8 1 4 5 4 5 8 1 1 8_
Here is the sum:
7+5+4+5+8+9+8+1+4+5+4+5+8+1+1+8=83
Here is the modulo 10 result: 83%10=3 and this is not a valid credit card number.
Compose a function luhn which correctly validates a given candidate 16-digit credit-card number (as a numeric input in int).
I have written the python code as per your requirements, kindly refer to comment line in code for better clarity.
I have also uploaded the output of the code.
# luhn function to validate whether a credit card number is valid or not
def luhn(card_num):
nDigits = len(card_num)
nSum = 0
# isSecond is flag variable used to check if the selected position is Second digit or not
isSecond = False
# loop to iterate throughout the number
for i in range(nDigits - 1, -1, -1):
d = ord(card_num[i]) - ord('0')
if (isSecond == True):
d = d * 2
if d > 9:
d -= 9
nSum +=d
isSecond = not isSecond
if (nSum % 10 == 0):
return True
else:
return False
# Driver code
if __name__=="__main__":
card_num = input('Enter the card number\n')
card_num = card_num.replace('.', '')
# to check it a 16-digit number or not
if len(card_num) < 16:
print('This is not a credit card number')
exit()
#validation function call
if (luhn(card_num)):
print("This is a valid credit card")
else:
print("This is not a valid credit card")