Issue
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.
Solution
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:
You don't need explicit
== True
inif
clauses.if cond
checks ifbool(cond)
isTrue
, and in your casecond
equalsTrue
already.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
Answered By - Lev Levitsky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.