Chapter 43: Credit Card Validatorยถ
๐ Open Notebookยถ
๐บ Video Tutorialยถ
Credit card validator in Python ๐ณ (8:49)
๐ What Youโll Learnยถ
Implement the Luhn algorithm to validate credit card numbers - a real-world application of mathematical algorithms!
๐ฏ Learning Objectivesยถ
Understand the Luhn algorithm (mod 10 algorithm)
Convert strings to lists of integers
Implement mathematical validation logic
Reverse and manipulate lists
Create practical validation tools
๐ Concept Explanationยถ
The Luhn Algorithmยถ
The Luhn algorithm (also called mod 10 algorithm) is used to validate credit card numbers, IMEI numbers, and other identification numbers.
How It Works:ยถ
Remove the last digit (check digit)
Reverse the remaining digits
Double every second digit
If doubled digit > 9, subtract 9
Sum all digits
Add the check digit
If total % 10 == 0, the number is valid
Example:ยถ
Credit card: 4532015112830366
Check digit: 6
Remaining: 453201511283036
Reversed: 630382115102354
Double every 2nd: 6,6,0,6,8,4,1,2,5,2,0,4,3,10,5,8
Subtract 9 if > 9: 6,6,0,6,8,4,1,2,5,2,0,4,3,1,5,8
Sum: 61
Add check digit: 61 + 6 = 67
67 % 10 = 7 โ 0, so invalid (this is just an example)
๐ก Examplesยถ
Basic Validatorยถ
def validate_card(card_number):
# Remove spaces and convert to string
card_number = card_number.replace(" ", "")
# Check if all characters are digits
if not card_number.isdigit():
return False
# Remove last digit (check digit)
check_digit = int(card_number[-1])
digits = [int(d) for d in card_number[:-1]]
# Reverse the digits
digits.reverse()
# Double every second digit
for i in range(1, len(digits), 2):
digits[i] *= 2
if digits[i] > 9:
digits[i] -= 9
# Sum all digits
total = sum(digits) + check_digit
# Check if divisible by 10
return total % 10 == 0
# Test
card = "4532015112830366"
if validate_card(card):
print("โ
Valid card number")
else:
print("โ Invalid card number")
Interactive Validatorยถ
def validate_card(card_number):
# Remove spaces and hyphens
card_number = card_number.replace(" ", "").replace("-", "")
# Validation checks
if not card_number.isdigit():
return False, "Card number must contain only digits"
if len(card_number) < 13 or len(card_number) > 19:
return False, "Card number must be between 13 and 19 digits"
# Luhn algorithm
check_digit = int(card_number[-1])
digits = [int(d) for d in card_number[:-1]]
digits.reverse()
for i in range(1, len(digits), 2):
digits[i] *= 2
if digits[i] > 9:
digits[i] -= 9
total = sum(digits) + check_digit
if total % 10 == 0:
return True, "Valid card number"
else:
return False, "Invalid card number"
# Main program
print("๐ณ Credit Card Validator")
print("-" * 30)
card = input("Enter card number: ")
is_valid, message = validate_card(card)
if is_valid:
print(f"โ
{message}")
else:
print(f"โ {message}")
With Card Type Detectionยถ
def get_card_type(card_number):
"""Identify the card type based on the first digits"""
if card_number.startswith('4'):
return "Visa"
elif card_number.startswith('5'):
return "Mastercard"
elif card_number.startswith('37'):
return "American Express"
elif card_number.startswith('6'):
return "Discover"
else:
return "Unknown"
def validate_card(card_number):
# Remove spaces and hyphens
card_number = card_number.replace(" ", "").replace("-", "")
if not card_number.isdigit():
return False, "Invalid format", None
if len(card_number) < 13 or len(card_number) > 19:
return False, "Invalid length", None
# Luhn algorithm
check_digit = int(card_number[-1])
digits = [int(d) for d in card_number[:-1]]
digits.reverse()
for i in range(1, len(digits), 2):
digits[i] *= 2
if digits[i] > 9:
digits[i] -= 9
total = sum(digits) + check_digit
card_type = get_card_type(card_number)
if total % 10 == 0:
return True, "Valid", card_type
else:
return False, "Invalid checksum", card_type
# Test
print("๐ณ Credit Card Validator")
print("-" * 40)
card = input("Enter card number: ")
is_valid, message, card_type = validate_card(card)
if is_valid:
print(f"โ
Valid {card_type} card")
else:
print(f"โ {message}")
if card_type != "Unknown":
print(f" Appears to be {card_type} format")
โ๏ธ Practice Exercisesยถ
Exercise 1: Basic Validatorยถ
Implement a simple Luhn algorithm validator that:
Takes a card number as input
Validates using Luhn algorithm
Prints valid or invalid
Exercise 2: Format Checkerยถ
Add validation for:
Only digits (or spaces/hyphens)
Correct length (13-19 digits)
No letters or special characters
Exercise 3: Batch Validatorยถ
Create a program that validates multiple cards from a file:
cards = [
"4532015112830366",
"6011514433546201",
"371449635398431",
"0000000000000000"
]
for card in cards:
is_valid, message, card_type = validate_card(card)
status = "โ
" if is_valid else "โ"
print(f"{status} {card}: {card_type} - {message}")
๐ Common Mistakesยถ
1. Not Reversing Before Doublingยถ
# โ Wrong - doubles wrong digits
for i in range(1, len(digits), 2):
digits[i] *= 2
# โ
Correct - reverse first
digits.reverse()
for i in range(1, len(digits), 2):
digits[i] *= 2
2. Forgetting to Subtract 9ยถ
# โ Wrong - doesn't handle > 9
digits[i] *= 2
# โ
Correct
digits[i] *= 2
if digits[i] > 9:
digits[i] -= 9
3. Including Check Digit in Sum Before Addingยถ
# โ Wrong - check digit doubled
digits = [int(d) for d in card_number]
# โ
Correct - exclude check digit
check_digit = int(card_number[-1])
digits = [int(d) for d in card_number[:-1]]
๐ฎ Real-World Applicationsยถ
E-commerce: Validate cards before processing
Payment Gateways: Pre-validation before API calls
Form Validation: Client-side card number checking
Testing: Generate valid test card numbers
Security: Quick check before expensive validation
๐ Challenge Projectsยถ
Challenge 1: Card Generatorยถ
Create valid test card numbers using the Luhn algorithm:
def generate_card(prefix, length):
# Generate random digits
# Calculate check digit using Luhn
# Return valid card number
pass
Challenge 2: Masked Displayยถ
Show card number with masking:
Input: 4532015112830366
Output: 4532 **** **** 0366
Challenge 3: Expiry Date Validatorยถ
Extend to validate:
Card number (Luhn)
Expiry date (MM/YY format, not expired)
CVV (3-4 digits)
๐ Key Takeawaysยถ
Luhn algorithm validates identification numbers
Reverse digits before doubling
Double every second digit (after reversing)
Subtract 9 if doubled digit > 9
Sum must be divisible by 10
Always validate format before applying algorithm
Card type can be identified from first digits
๐ Key Takeaways from Videoยถ
Lists store multiple items in a single variable
Use loops to repeat actions
Use if-elif-else for conditional logic
๐ก These points cover the main concepts from the video tutorial to help reinforce your learning.
๐ Next Chapterยถ
Continue to Chapter 44: Banking Program to build a complete banking application!
Security Note: This validates the format only. Real validation requires checking with the card issuer. Never store card numbers in plain text!