# Credit card validator

I am stuck trying to solve a problem on sololearn app.

Problem description -

You need to verify if the given credit card number is valid. For that you need to use the Luhn test.

Here is the Luhn formula:

1. Reverse the number.
2. Multiple every second digit by 2.
3. Subtract 9 from all numbers higher than 9.
4. Add all the digits together.
5. Modulo 10 of that sum should be equal to 0.

Given a credit card number, validate that it is valid using the Luhn test. Also, all valid cards must have exactly 16 digits.

Input Format:
A string containing the credit card number you need to verify.

Output Format:
A string: ‘valid’ in case the input is a valid credit card number (passes the Luhn test and is 16 digits long), or ‘not valid’, if it’s not.

Sample Input:
4091131560563988

Sample Output:
valid

My solution -

``````cc_number = input()
cc_number = list(map(int,cc_number))
cc_number.reverse()

for i in range(1,16,2):
cc_number[i]*=2
for i in range(16):
if cc_number[i]>9:
cc_number[i] -=9

sum_cc = sum(cc_number)

if sum_cc % 10 == 0 and len(cc_number)==16:
print("valid")
else:
print ("not valid")
``````

This code gives correct output in some cases but fails 2 out of 7 test cases. Can you help me find the error in my code?? Thanks in advance!!

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (`</>`) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like