My code output is incorrect even though I can't see why.If anyone could shed some light on my problem, I would really appreciate it.
For an assignment we are to allow the user to input a 15 or 16 digit credit card number and return whether the number given is valid.
we are using the Luhn's test to verify the number and this is where my code isn't working. the card number 4222222222222220 should return as valid, but mine isn't working and I believe its because I'm not fully understanding what the code is meant to do.
Luhn's Test: Let us say that the credit card number was made of the following digits:
d15 d14 d13 d12 d11 d10 d9 d8 d7 d6 d5 d4 d3 d2 d1 d0
The last digit d0 is the check digit in the Luhn's algorithm. The algorithm goes as follows:
Multiply all the odd digits d1, d3, … d15 by 2.
Sum the digits of each product.
Now add all the even digits d0, … d14 and the single digit products of the odd digits.
If the final sum is divisible by 10 then the credit card is valid, otherwise it is invalid.
My code is:
def len_check(x):
length = len(str((x)))
if (length == 15) or (length == 16):
return True
else:
return False
def is_valid(x):
card = x
num_list= list((str(card)))
sum_odd = 0
sum_even = 0
even_count = 0
odd_count = 0
total_sum = 0
length = 0
for i in num_list:
length += 1
print(length)
count = 0
if length == 16:
odd_count = 15
even_count = 14
if length == 15:
odd_count = 13
even_count = 14
print(even_count)
print(odd_count)
while (count <= length-2):
print('even count', even_count)
print('D-even', num_list[even_count])
sum_even += int(num_list[even_count])
even_count -=2
print('sum even', sum_even)
print('odd count', odd_count)
print('D-odd', num_list[odd_count])
prod = 2 * int(num_list[odd_count])
sum_odd += prod
odd_count -=2
print('sum odd', sum_odd)
count +=2
total_sum = sum_odd + sum_even
print('total sum', total_sum)
if total_sum % 10 == 0:
return True
else:
return False
def main():
cc_num = int(input('Enter at 15 or 16-digit credit card number: '))
if not len_check(cc_num):
print('Not a 15 or 16-digit number')
else:
if not is_valid(cc_num):
print('Invalid credit card number')
else:
print('valid card number')
main()