Last active
August 16, 2023 12:14
-
-
Save thinkphp/5107438 to your computer and use it in GitHub Desktop.
Luhn Python checksum for credit card validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Luhn Python checksum for credit card validation | |
import sys | |
def luhn(n): | |
sum = 0 | |
alt = 0 | |
i = len(n) - 1 | |
num = 0 | |
while i >= 0: | |
num = int( n[ i ] ) | |
if alt: | |
num = num * 2 | |
if num > 9: | |
num = ( num % 10 ) + 1 | |
sum = sum + num | |
alt = not alt | |
i -= 1 | |
return sum%10 == 0 | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print"Usage: python lyhn.py 121232232" | |
sys.exit() | |
n = str(sys.argv[1]) | |
if luhn( n ): | |
print "VALID" | |
else: | |
print "INVALID" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment