0

I'm very much new to programming. I implemented Credit card validation program according to following instructions.

  1. Let the input be input.
  2. Reverse input.
  3. Multiply all odd positions (i.e. indexes 1, 3, 5, etc.) of input by 2. If any of these multiplied entries is greater than 9, subtract 9.
  4. Sum all of the entries of input, store as sum.
  5. If sum (mod 10) is equal to 0, the credit card number is valid.

code

# credit card validation - Luhn Formula

card_number = list(reversed(input("enter card number: ")))
status = False
temp1 = []
temp2 = []
sum = 0

for i in card_number:
    if card_number.index(i) % 2 != 0:
        temp1.append(int(i) * 2)
    else:
        temp1.append(int(i))

for e in temp1:
    if e > 9:
        temp2.append(e - 9)
    else:
        temp2.append(e)

for f in temp2:
    sum += f

if sum % 10 == 0:
    status = True
    print("card is VALID")
else:
    print("card is INVALID")

code sometimes works and sometimes not. is there a problem with my code.

valid number 49927398716 - works
valid number 4916092180934319 - not working

please don't link to this - Implementation of Luhn Formula I don't need another implementation. If possible please tell me what's wrong with my code. So I can correct it.

Thank you

Amirtha
  • 7
  • 5
  • Possible duplicate of [Implementation of Luhn Formula](https://stackoverflow.com/questions/21079439/implementation-of-luhn-formula) – Confusion Matrix May 17 '18 at 05:46
  • @sikoliaWycliffe well thank you. I actually need to know what's wrong with this code. not another way to implemented this. – Amirtha May 17 '18 at 05:49
  • 1
    Needs more [mcve] ("*sometimes works and sometimes not*" is not a problem description). – melpomene May 17 '18 at 05:53
  • @melpomene thanks. made some changes. please have a look. – Amirtha May 17 '18 at 05:57
  • 1
    https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – melpomene May 17 '18 at 05:57
  • @melpomene I went through the article. It's great! I went through few steps but I don't know how to implement test cases. Any help is appreciated. This is actually 2nd program I ever wrote. First one was a lottery. – Amirtha May 17 '18 at 06:10

1 Answers1

1

Your problem is here:

if card_number.index(i) % 2 != 0:

This looks for a specific digit in the number, but if the digit is repeated, you will get the position of the first occurrence. If both (or all, or no) occurrences are in odd positions, your code will work. But if one is in an even position and another not, then your odd/even test will produce the wrong answer. Do the odd/even position check this way:

for n,i in enumerate(card_number):
    if n % 2 != 0:
        temp1.append(int(i) * 2)
    else:
        temp1.append(int(i))
BoarGules
  • 16,440
  • 2
  • 27
  • 44