luhn algorithm code example
Example 1: luhn's algorithm python
def split_char(number_string):
return [char for char in number_string]
def list_str_to_int(test_list):
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
return test_list
def list_int_to_str(test_list):
for i in range(0, len(test_list)):
test_list[i] = str(test_list[i])
return test_list
def list_multiplied_by_2(test_list):
for i in range(0, len(test_list)):
test_list[i] *= 2
return test_list
ccn = int(input("Enter your digital card number: "))
ccn = str(ccn)
if 12 > len(ccn) < 17:
print("INVALID")
exit()
num1 = " " + "".join(ccn[::-1])
num2 = "".join(ccn[::-1])
num3 = "".join(num1[::2])
num4 = "".join(num2[::2])
alternate_num3 = num3.replace(" ", "")
sep1 = split_char(alternate_num3)
sep2 = split_char(num4)
str_to_int1 = list_str_to_int(sep1)
str_to_int2 = list_str_to_int(sep2)
str_2_1 = list_multiplied_by_2(str_to_int1)
int_to_str1 = list_int_to_str(str_2_1)
sep_digits1 = ""
for i in int_to_str1:
sep_digits1 += "".join(i)
sep3 = split_char(sep_digits1)
str_to_int3 = list_str_to_int(sep3)
sum_last_add1 = sum(str_to_int3)
sum_last_add2 = sum(str_to_int2)
checksum = sum_last_add1 + sum_last_add2
if checksum % 10 == 0:
if ccn[:2] == "34" or "37" and len(ccn) == 15:
print("AMEX")
elif ccn[:1] == "4" :
if len(ccn) == 13 or 14 or 15 or 16:
print("VISA")
elif ccn[:2] == "51" or "52" or "53" or "54" or "55" :
if len(ccn) == 16:
print("MASTERCARD")
else:
print("INVALID")
else:
print("INVALID")
Example 2: luhn algorithm python
$ pip install fast-luhn