Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Validation - Postal Code

I have been posed the following problem:

Define a function postalValidate(S) which first checks if S represents a postal code which is valid: first, delete all spaces; the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers. If S is not a valid postal code, return the boolean False. If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.

Here is my code:

def postalValidate(S):
S = S.replace(" ", "")
   for c in range(0, 4, 2):
      if S[c].isalpha() == True:
         x = True
   for c2 in range(1, 5, 2):
      if S[c2].isdigit() == True:
         y = True
   if x == True and y == True:
            return S.upper()
   else:
      return False

Problem is, I get this error:

UnboundLocalError: local variable 'y' referenced before assignment

Help with this would be greatly appreciated.

like image 957
Dan Avatar asked Aug 02 '26 06:08

Dan


1 Answers

The problem is that if the condition S[c2].isdigit() == True is not met, the variable y is not assigned and so you can't check if it's True later. The easiest way to avoid it is to assign it the value of False in advance:

y = False
for c2 in range(1, 5, 2):
    if S[c2].isdigit():
       y = True

A couple of notes:

  1. You don't need explicit == True in if clauses. if cond checks if bool(cond) is True, and in your case cond equals True already.

  2. The result of the range function doesn't include its second argument:

    In [1]: list(range(0, 4, 2))
    Out[1]: [0, 2]
    

    You probably want to add 1 to it:

    In [2]: list(range(0, 5, 2))
    Out[2]: [0, 2, 4]
    

Also you can use the slice notation to avoid loops altogether.

So a couple of optimizations can reduce the length of your code:

def postValidate(s):
    s = s.replace(' ', '')
    if len(s) == 6 and s[0:5:2].isalpha() and s[1:6:2].isdigit():
       return s.upper()
    return False
like image 73
Lev Levitsky Avatar answered Aug 03 '26 20:08

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!