DEV Community

Vigneshwaran V
Vigneshwaran V

Posted on

Python Practice: Credit Card Number Validation Using Luhn Algorithm

Today I practised a Python program to check whether a given credit card number is valid using the Luhn Algorithm.

Question

Write a Python program to validate the given credit card number using the Luhn Algorithm.

Code

num = 4532015112830366
copy = num
total=0
digit=0
while copy>0:
    digit=digit+1
    copy=copy//10

pos=digit

while num>0:
    last=num%10
    if pos%2!=0:
        multi=last*2
        if(multi>9):
            l=multi%10
            f=multi//10
            total=total+l+f
        else:
            total=total+multi
    else:
        total=total+last
    num//=10
    pos-=1

print(f"total: {total}")

if total%10 == 0:
    print("Valid Credit Card Number")
else:
    print("Invalid Credit Card Number")


Enter fullscreen mode Exit fullscreen mode

Output

total: 60
Valid Credit Card Number
Enter fullscreen mode Exit fullscreen mode

Top comments (0)