Skip to main content

Luhn Algorithm in Python

The Luhn Algorithm, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, and more. It's often used to check whether a given number is potentially valid based on its checksum digit. Here's a Python function to perform the Luhn check:

 def luhn_check(num):
    # Convert the number to a list of digits in reverse order
    arr = [int(x) for x in str(num)][::-1]

    # Remove the last digit (checksum digit)
    last_digit = arr.pop(0)

    # Calculate the Luhn sum
    total = sum(val if i % 2 != 0 else ((val * 2) % 9) or 9 for i, val in enumerate(arr))

    # Add back the last digit
    total += last_digit

    # Check if the total is divisible by 10
    return total % 10 == 0

Explantion of Luhncheck Algorithm

  1. def luhn_check(num):: This line defines a function called luhn_check that takes an input num, which is the number you want to validate using the Luhn algorithm.

  2. arr = [int(x) for x in str(num)][::-1]: This line converts the input num into a list of digits in reverse order. It does the following:

    • str(num): Converts the number to a string so that we can iterate through its digits.
    • [int(x) for x in str(num)]: Uses a list comprehension to convert each character (digit) in the string back to an integer, creating a list of digits.
    • [::-1]: Reverses the list so that we can start processing from the rightmost digit (the last digit).
  3. last_digit = arr.pop(0): This line removes and stores the rightmost digit (the checksum digit) from the list arr.

  4. total = sum(val if i % 2 != 0 else ((val * 2) % 9) or 9 for i, val in enumerate(arr)): This line calculates the Luhn sum. It uses a generator expression and the sum function to iterate through the list of digits and perform the following operations for each digit:

    • enumerate(arr): Enumerates through the list arr, providing both the index i and the digit val.
    • (val if i % 2 != 0 else ((val * 2) % 9) or 9): For each digit, it checks if the index i is odd (i % 2 != 0). If it's odd, it uses the original digit val. If it's even, it doubles the digit using (val * 2), and if the result is greater than 9, it subtracts 9 (((val * 2) % 9) or 9). This step handles the doubling and subtracting 9, if necessary, for every second digit.
  5. total += last_digit: Adds back the rightmost digit (the checksum digit) to the total.

  6. return total % 10 == 0: Checks if the total is divisible by 10. If it is, the function returns True, indicating that the input number is valid according to the Luhn algorithm. Otherwise, it returns False.

# Example usage:
card_number = "79927398713"
if luhn_check(card_number):
    print(f"{card_number} is a valid card number.")
    print(f"{card_number} is not a valid card number.")


In summary, this concise Python implementation converting the input number to a list of digits in reverse order, applying the Luhn algorithm operations, and checking the result for divisibility by 10 to determine its validity.

Post Tags: