Skip to content

Commit 91352ed

Browse files
author
Karan Goel
committed
Credit Card Validator done
1 parent 000e25d commit 91352ed

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Numbers/credit_card_validator.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Credit Card Validator - Takes in a credit card number from a
3+
common credit card vendor (Visa, MasterCard, American Express,
4+
Discoverer) and validates it to make sure that it is a valid
5+
number (look into how credit cards use a checksum).
6+
7+
This program works with *most* credit card numbers.
8+
9+
Uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm).
10+
11+
1. From the rightmost digit, which is the check digit, moving
12+
left, double the value of every second digit; if product of this
13+
doubling operation is greater than 9 (e.g., 7 * 2 = 14), then
14+
sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5).
15+
16+
2. Add together doubled digits with the undoubled digits from the
17+
original number.
18+
19+
3. If the total modulo 10 is equal to 0 (if the total ends in zero)
20+
then the number is valid according to the Luhn formula; else it is
21+
not valid.
22+
"""
23+
24+
if __name__ == '__main__':
25+
number = raw_input('Enter the credit card number of check: ').replace(' ', '')
26+
#if not number.isdigit():
27+
# raise Exception('Invalid credit card number. Make sure it\'s all digits (with optional spaces in between).'
28+
29+
digits = [int(char) for char in number]
30+
31+
# double alternate digits (step 1)
32+
doubled = [(digit * 2) if (i % 2 == 0) else digit \
33+
for (i, digit) in enumerate(digits)] # i <3 python
34+
# sum digits of number > 10 (step 2)
35+
summed = [num if num < 10 else sum([int(dig) for dig in str(num)]) \
36+
for num in doubled] # i <3 python ** 2
37+
# step 3
38+
if sum(summed) % 10 == 0:
39+
print 'The number is valid'
40+
else:
41+
print 'The number is invalid'

0 commit comments

Comments
 (0)