In: Computer Science
I am creating a program in Python that allows the user to input a credit card number, and determine if the card is valid. This should be done by taking every other number, starting from the right, and adding them together. The doubling each of the other digits, and adding them together as single digits, and then adding the two sums together. For example, if the number 4833 1200 3412 3456 is used, the first sum should be 6+4+2+4+0+2+3+8=29, the second sum would be 1+0+6+2+6+0+2+6+8=31. Adding the two sums together should be 60. A number that is divisible by 10, ex 60, would be a valid number. A number that is not divisible by 10, ex 35, is not a valid number.
After the validity of the card is determined, the program must then determine what the "check number" should be if the card is not valid. This would be the very last number of the card sequence. For example, if the number 5424 1810 5676 1902 is given, the program should see the number is invalid and determine the last number should be a 6 instead of a 2 for the card to be valid.
My current code tells if the cards is valid or not but should also accept numbers with any number of spaces in between, I'm not sure how to fix that either. Here is my code so far:
creditCardNum=input("Enter card number")
def sum_digits(n):
r=0
while n:
r, n=r + n %10 , n//10
return r
sum1=0
sum2=0
for i in range(1,len(creditCardNum),2):
sum1=sum1+int(creditCardNum[i])
for i in range(0,len(creditCardNum),2):
data=2*int(creditCardNum[i])
sum2=sum2+sum_digits(data)
total=sum1+sum2
total=str(total)
if total[-1]=='0':
print("The card is valid")
else:
print("The card is not valid")
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
creditCardNum=input("Enter card number : ")
#remove unnecessary spaces
creditCardNum = creditCardNum.replace(" ","")
def sum_digits(n):
r=0
while n:
r, n=r + n %10 , n//10
return r
sum1=0
sum2=0
for i in range(1,len(creditCardNum),2):
sum1=sum1+int(creditCardNum[i])
for i in range(0,len(creditCardNum),2):
data=2*int(creditCardNum[i])
sum2=sum2+sum_digits(data)
total=sum1+sum2
remain = total%10
if remain==0:
print("The card is valid")
else:
cardLastNum = int(creditCardNum[-1])
print("The card is not valid")
remainVal = cardLastNum+10-remain
remainVal = remainVal%10
print("The last digit should be %d instead of
%d"%(remainVal,cardLastNum))