1

I got the solution for validating credit card number and I want to understand the logic behind the second if statement:

if 2*num_list_rev[i]>9:
                double = double + 2*num_list_rev[i] - 9

I am new to coding so sensing this may be a way of handling 2 digit number but don't understand why we minus 9 from the multiplied figure?

num_list = [int(char) for char in number]
num_len = len(num_list)
num_list_rev = num_list[::-1]
double = 0
single = 0
for i in range(0,num_len):
    if i%2 != 0:
        if 2*num_list_rev[i]>9:
            double = double + 2*num_list_rev[i] - 9
        else:
            double = double + 2 * num_list_rev[i]
    else:
        single = single + num_list_rev[i]

if (double+single)%10 == 0:
    print(f'{number} is a valid credit card number.')
else:
    print(f'{number} is not a valid credit card number.')
  • The reason for subtracting 9 has nothing to do with Python or coding. It is a question about the design of the Luhn algorithm, which specifies that operation. If no answer turns up on Stack Overflow, you could try the [Computer Science](https://cs.stackexchange.com/) site. – Dennis Sparrow Jun 17 '20 at 18:51
  • Thanks @Dennis Sparrow. I understood this is related to math as the result of (sum of all digits ) is equal to (sum of digit greater then 9 minus 9) and (sum of digit less then 9). – Sumaira Awan Jun 18 '20 at 07:48

0 Answers0