I was trying to implement the Luhn Formula in Python. Here is my code:
import sys
def luhn_check(number):
if number.isdigit():
last_digit = int(
There are some errors in your code:
result = divmod(sum_of_digits, 10)
returns a tuple, you need only modulo, that is use
result = sum_of_digits % 10
Second, to check for validity, you don't omit last digit (that is checksum), but include it in computations. Use
reverse_sequence = list(int(d) for d in str(int(number[::-1])))
And check for result being zero:
if not result:
print("[VALID] %s" % number)
Or if you insist on keeping this not needed complexity, check for last digit to be inverse of checksum modulo 10: keep
reverse_sequence = list(int(d) for d in str(int(number[-2::-1])))
but use
if (result + last_digit) % 10 == 0:
print("[VALID] %s" % number)
For a simplier and shorter code, I can give you a reference to my older answer.