Credit Card Validator in Python

General questions regarding Linux.

Moderators: Terry, FWLUG Administrator

Credit Card Validator in Python

Postby Brian » Mon Aug 13, 2012 11:24 pm

Hey guys this is the code to the credit card Validator in Python. Just so you aren't confused here are the steps to the check used in this program (also called a "Luhn Check"):

1) Take the credit card number and double every other digit, starting with the first one
2) Add up the 16 numbers in the credit card number to get a sum
3) If the sum is divisible by 10, its a valid credit card number

Also, the first number tells you what company the card is from.

Code: Select all
#!/usr/bin/env python

def LuhnCheck(CCnumber):
   """Uses a Luhn check to determine the validity of a credit card number(CCnumber must be submitted as a string)"""
   testResult=0
   companyNum=int(CCnumber[0])
   for num in range(16):

      if num%2==0:#in this case, if item is odd
         double=int(CCnumber[num])+int(CCnumber[num])#double the number

         if(CCnumber[num]>=5):
            #take the number "double" and add the digits together
            #i.e.: 10 becomes 1, 12 becomes 3, etc...
            for c in str(double):
               testResult+=int(c)
               
         else:
            #otherwise, just add double to the test result
            testResult+=double

      else:
         testResult+=int(CCnumber[num])


   if testResult%10==0: #if testResult is divisible by ten, it is valid
      print "This is a valid credit card number!\n"

      #Now, lets find out what company makes the card...
      if companyNum==3:
         print "The Company attached to this card is American Express."
      elif companyNum==4:
         print "The Company attached to this card is Visa."
      elif companyNum==5:
         print "The Company attached to this card is MasterCard."
      elif companyNum==6:
         print "The Company attached to this card is Discover."
      else:
         print "The Company attached to this card is Unknown."

   else:
      print "This is a fake credit card number."


Happy coding!
Brian
 
Posts: 1
Joined: Sat Aug 11, 2012 3:54 pm

Return to FWLUG General Discussions

Who is online

Users browsing this forum: Google [Bot] and 17 guests

cron