Validate PAN card number format in Python

Hello, Welcome. Here you shall learn how to validate Pan Number Format in Python programming.

PAN stands for Permanent Account Number, circulated to each and every taxpayer by the Income-tax department.

PAN is a 10 digit well-distinct alphanumeric number.

Now let’s see how we can validate it in Python.

Validate PAN number format in Python

To validate we need to import the RE module.
RE stands for Regular Expression. This module contains various functions that perform functions like compile, etc.

RE module- Compile() function validates the given string to that of the specified pattern.

The RE module consists of some special characters called metacharacters.  Few of them are as follows:

  1. ^ –> Identifies the beginning of a string.
  2. $ –> Recognizes end of the string.
  3. ? –> This resembles zero or one occurrence.

Now let’s look into the required code.

import re 
def isValid(Z): 
    return Result.match(Z) 
# Driver Code 
if (isValid(Z)):  
    print ("It's a Valid PAN Number")      
else : 
    print ("Invalid PAN Number entered.")

In our code, we have imported the RE module.
Next, we have a function defined to compute the given input is valid or not.
The Compile function takes the set of formats through which it does validation accordingly.

In our  code, the format shall be ” [A-Za-z]{5}\d{4}[A-Za-z]{1} ” . Let’s understand what the format says,
1. [A-Za-z]–>Indicates that the alphabets can be anything between A-Z, it can either be in uppercase or lowercase.
2. {5}–> Tells that the above letters need to be 5 in the count.
3. \d–> Tells it should be digits between 0-9.
4. {4}–>Tells that there should be 4 digits.
5. [A-Za-z]–> Again followed by alphabets.
6. {1}–> Indicate that there is only 1 alphabet at the end.

We have used variable Z to store the input string. The Input() method can also be used to get user input.
The string is then passed to the IsValid() to check for validity. The result after compilation is stored in the variable Result.

OUTPUT for the above code :

It’s a Valid PAN number.


If we give input as “ABC5d7896B”, then the output is

Invalid PAN number entered.

Leave a Reply

Your email address will not be published. Required fields are marked *