ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Python Luhn checksum for credit card validation
Submitter: David Shaw (other recipes)
Last Updated: 2003/01/08
Version no: 1.0
Category: Algorithms

 

5 stars 4 vote(s)


Description:

This is an industry standard algorithm I ported to python. It works on all major credit cards. You pass in the credit card number as a string and it returns 1 for a valid card or 0 for an invalid card

Source: Text Source

def cardLuhnChecksumIsValid(card_number):
    """ checks to make sure that the card passes a luhn mod-10 checksum """

    sum = 0
    num_digits = len(card_number)
    oddeven = num_digits & 1

    for count in range(0, num_digits):
        digit = int(card_number[count])

        if not (( count & 1 ) ^ oddeven ):
            digit = digit * 2
        if digit > 9:
            digit = digit - 9

        sum = sum + digit

    return ( (sum % 10) == 0 )

Discussion:

This recipe was originally written for a now-defunct e-commerce application used within Zope.

It will save you time and money before trying to process a bad card with your credit card vendor, because you won't waste money trying to authorize a bad card with your credit card processing vendor.

The full suite of creditValidation methods are available here:

http://david.theresistance.net/files/creditValidation.py



Add comment

Number of comments: 6

Checksum calculation, Not specified Not specified, 2004/07/01

""" easy checksum """
def checksum(a):
    return (10 - sum([int(y)*[7,3,1][x%3] for x, y in enumerate(str(a)[::-1])])%10)%10

Add comment

That checksum is wrong., Christopher Dunn, 2005/02/07
It does not match the other 2 listed here, and it returns "7" for my credit card. What is it for?
Add comment

Another take..., sasa sasa, 2004/10/19

# Return the "Luhn transform" of a digit.
luhnify = lambda digit: sum(divmod( digit*2, 10 ))

def luhn_checksum( digits ):
    """Return the Luhn checksum of a sequence of digits.
    """
    digits = map( int, digits )
    odds, evens = digits[-2::-2], digits[-1::-2]
    return sum( map(luhnify,odds) + evens ) % 10

Add comment

Integer only version, Lloyd Girty, 2006/02/22
Here is a integer-only version that avoids string casts. You may need "from __future__ import division" to use the "//" floor operator.

def luhn(n):
    """luhnsum(int)->bool
    Mod 10 checksum by Hans Peter Luhn (1896–1964)
    """
    sum=0
    while n:
        r=n%100
        n//=100
        z=r%10
        r=r//10*2
        sum+=r//10+r%10+z
    return 0==sum%10

Add comment

generating many luhn numbers, Lloyd Girty, 2006/02/22

def nextLuhn(n):
    """nextLuhn(int) -> int
    Gets the smallest Luhn number greater than n.
    Uses a naive (exhaustive) algorithm that must try
    the Luhn checksum an average of 10 times.
    """
    n+=1
    while not luhn(n):
        n+=1
    return n

def biggerLuhn(n):
    """ biggerLuhn(int) -> int
    Gets a Luhn number greater than n.
    Uses a probability model that is very efficient if
    n passes the Luhn checksum. 
    It may be possible to miss a Luhn number with this method.
    """
    for t in [8, 18, 7, 17, 6, 16]:
        if luhn(n+t):
            return n+t
    return nextLuhn(n)
    
def xluhn(seed,howmany):
    """xluhn(int,int) ->*int
    Yields Luhn numbers greater than the seed.
    Some numbers may be left out of the sequence.
    """
    while howmany:
        seed=biggerLuhn(seed)
        howmany-=1
        yield seed

Add comment

Incorrect LUHN checksum implementation, James Coe, 2007/08/15
This LUHN implementation is actually incorrect. The card number digits must be traversed from end to beginning (reverse the direction the for loop counts) or some (but not all) perfectly valid card numbers will be rejected.
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.