Python program to check credit card number is valid or not

PythonServer Side ProgrammingProgramming

Suppose we have a credit card number. We have to check whether the card number is valid or not. The card numbers have certain properties −

  • It will start with 4, 5 and 6

  • It will be 16 digits’ long

  • Numbers must contain only digits

  • It may have digits in four groups separated by '-'

  • It must not use any other separator like space or underscore

  • It must not have 4 or more consecutive same digits

So, if the input is like s = "5423-2578-8632-6589", then the output will be True

To solve this, we will follow these steps −

  • if number of '-' in s is greater than 0, then
    • a := a list of parts separated by "-"
    • p:= 1
    • if size of a is not same as 4, then
      • p:= null
      • a:= blank list
    • for each b in a, do
      • if size of b is not same as 4, then
        • p:= null
        • come out from loop
  • otherwise,
    • p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits long
    • s := remove "-" from s
    • q := search substring where 4 or more consecutive characters are same
    • if p is not null and q is null, then
      • return True
    • otherwise,
      • return False


Let us see the following implementation to get better understanding

import re

def solve(s):
   if s.count("-")>0:
      a = s.split("-")
      if len(a)!=4:
      for b in a:
         if len(b)!=4:
            p ="[456][0-9]{15}",s)
         s = s.replace("-","")
         q =".*([0-9])\\1{3}.*",s)

         if p!=None and q==None:
            return True
            return False

s = "5423-2578-8632-6589"




Published on 12-Oct-2021 09:05:26