[Tutor] n.isalnum() is failing

Alan Gauld alan.gauld at btinternet.com
Tue Jul 3 22:42:33 CEST 2007


"Terry" <terry.kemmerer at gmail.com> wrote

> trapping for possible user  errors.
> I am using x.isalnum() to check that I have a number

First, alnum() checks for alpha-numeric characters so
will allow both alphabetic characters and numerics.

BUT in python its better to ask forgiveness that permission
so don't bother doing the check but catch the errors when
they occur:

try:        start = int(start); end = int(end)
except: ValueError: start = None  # or whatever you prefer

> def leap(yyyy):
>    answer = 0
>    t1 = yyyy / 4
>    if t1 == int(t1):

For integer division this will always be true.

>        t2 = yyyy / 100
>        t3 = yyyy / 400
>        if t2 <> int(t2) or t3 == int(t3):

and similarly the second test will always be true.

>            answer = "-- leap year!"

thus this will always be true.

> start = raw_input("Enter yyyy for beginning year : ")
> end = raw_input("Enter yyyy for ending year : ")

The easiest way to solve your conversion problems
is to do it at source so wrap raw_input in a call to int()
and wrap both prompts in a try/except as shown above.

try:
   start = int(raw_input....)
   end = int(raw_input....)
except ValueError: pass # do something with error

> if len(start) == 4 and len(end) == 4:

that way you don't need these lines but can instead
test if the numeric value is greater than some lower
limit

>    if start.isalnum() == 1 and end.isalnum() == 1:
> #<----------fails to detect 'aaaa' as not a number
>        start = int(start); end = int(end)
> #<----------commits suicide here
>        if start > 0 and end > start:

As you are doing it start can never be less than 1000
(unless the user enters 0001 I suppose...)

Also in Python you can use the neater style of

if 0 < start < end:

to test whether start lies between 0 and end.

>            for i in range(start, end + 1):
>                answer = leap(i)
>                if answer != 0:

Its best not to mix return types in a function. If it is a
leap year you return a string. If it's not, you return a
number - 0. It would probably be better for the function
to return a boolean: True if it is a leap year and False
if not. That style of function is often called a predicate
and is usually named with an 'is' in front so it would
become isLeapYear() Then this test becomes the more
readable

for y in range(start, end+1):  # use y for year instead of meaningless 
i
      if isLeapYear(y):
         print i, 'is a leap year'

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list