Skip to content

Instantly share code, notes, and snippets.

@storlak
Last active January 16, 2024 21:36
Show Gist options
  • Save storlak/5394ce2f706ac7423eed29fa789a6d6e to your computer and use it in GitHub Desktop.
Save storlak/5394ce2f706ac7423eed29fa789a6d6e to your computer and use it in GitHub Desktop.
Checking credit card number validity. Use test credit card numbers.md file to check the validity of cards.
# Checking Credit Card validity
# 1. Remove any '-' or ' '
# 2. Add all digits in the odd places from right to left.
# 3. Double every second digit from right to left.
# (If result is a two-digit number,
# add the two-digit number together to get a single digit.)
# 4. Sum the totals of steps 2 & 3
# 5. If sum is divisible by 10, the credit card # is valid.
# Use testcardnumbers.txt file to check via test credit card numbers.
sum_odd_digits = 0
sum_even_digits = 0
total = 0
# step 1
card_number = input("Enter a card number: ")
card_number = card_number.replace("-", "")
card_number = card_number.replace(" ", "")
card_number = card_number[::-1]
# step 2
for x in card_number[::2]:
sum_odd_digits += int(x)
# step 3
for x in card_number[1::2]:
x = int(x * 2)
if x >= 10:
sum_even_digits += 1 + (x % 10)
else:
sum_even_digits += x
# step 4
total = sum_even_digits + sum_odd_digits
# step 5
if total % 10 == 0:
print("VALID CREDIT NUMBER")
else:
print("INVALID CREDIT CARD NUMBER")
# Test Credit Card Account Numbers
1. American Express 378282246310005
2. American Express 371449635398431
3. American Express Corporate 378734493671000
4. Australian Bankcard 5610591081018250
5. Diners Club 30569309025904
6. Diners Club 38520000023237
7. Discover 6011111111111117
8. Discover 6011000990139424
9. JCB 3530111333300000
10. JCB 3566002020360505
### Master&Visa Card Test Numbers
1. MasterCard 5555555555554444
2. MasterCard 5105105105105100
3. Visa 4111111111111111
4. Visa 4012888888881881
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment