Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Social Security Number Check - Python

Writing a program that prompts the user to enter a social security number in the format ddd-dd-dddd where d is a digit. The program displays "Valid SSN" for a correct Social Security number or "Invalid SSN" if it's not correct. I nearly have it, just have one issue.

I'm not sure how to check if it's in the right format. I can enter for instance:

99-999-9999

and it'll say that it's valid. How do I work around this so that I only get "Valid SSN" if it's in the format ddd-dd-dddd?

Here's my code:

def checkSSN():
ssn = ""
while not ssn:  
    ssn = str(input("Enter a Social Security Number in the format ddd-dd-dddd: "))
    ssn = ssn.replace("-", "") 
    if len(ssn) != 9: # checks the number of digits
        print("Invalid SSN")
    else:
        print("Valid SSN")
like image 628
user3105664 Avatar asked Jan 27 '26 17:01

user3105664


2 Answers

You can use re to match the pattern:

In [112]: import re

In [113]: ptn=re.compile(r'^\d\d\d-\d\d-\d\d\d\d$')

Or r'^\d{3}-\d{2}-\d{4}$' to make the pattern much readable as @Blender mentioned.

In [114]: bool(re.match(ptn, '999-99-1234'))
Out[114]: True

In [115]: bool(re.match(ptn, '99-999-1234'))
Out[115]: False

From the docs:

'^'
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
'$'
Matches the end of the string or just before the newline at the end of the string

\d
When the UNICODE flag is not specified, matches any decimal digit; this is equivalent to the set [0-9].
like image 78
zhangxaochen Avatar answered Jan 29 '26 06:01

zhangxaochen


How about this:

SSN = raw_input("enter SSN (ddd-dd-dddd):")
chunks = SSN.split('-')
valid=False
if len(chunks) ==3: 
   if len(chunks[0])==3 and len(chunks[1])==2 and len(chunks[2])==4:
       valid=True
print valid
like image 26
David Marx Avatar answered Jan 29 '26 06:01

David Marx