2024-05-12 07:44:49 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# Luhn Algorithm Example - Developed by acidvegas in Python (https://git.acid.vegas/msr90)
|
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
def modulo10(card_number: str) -> str:
|
|
|
|
'''
|
|
|
|
Validate a card number using the Luhn Algorithm
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
:param card_number: The card number to validate
|
|
|
|
'''
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
digits = [int(d) for d in card_number]
|
|
|
|
total_sum = 0
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
for i, digit in enumerate(reversed(digits)):
|
|
|
|
if i % 2 == 0:
|
|
|
|
digit = digit * 2
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
if digit > 9:
|
|
|
|
digit -= 9
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
total_sum += digit
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
check_digit = (10 - total_sum % 10) % 10
|
|
|
|
full_card_number = card_number + str(check_digit)
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
if (total_sum + check_digit) % 10 != 0:
|
|
|
|
raise ValueError('failed luhn check (non-divisible by 10)')
|
|
|
|
|
|
|
|
return full_card_number
|
2024-05-12 07:44:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-05-12 08:01:54 +00:00
|
|
|
card_number = input('Enter your card number without the last digit: ')
|
|
|
|
|
|
|
|
if not card_number.isdigit():
|
|
|
|
raise ValueError('invalid card number')
|
2024-05-12 07:44:49 +00:00
|
|
|
|
2024-05-12 08:01:54 +00:00
|
|
|
print(f'Full card number: {modulo10(card_number)}')
|