[Tutor] n.isalnum() is failing
Wolfram Kraus
wolfram.kraus at fen-net.de
Tue Jul 3 10:38:32 CEST 2007
Use isdigit instead of isalnum.
HTH,
Wolfram
On 03.07.2007 09:51, Terry wrote:
> Hi!
>
> I am running Python 2.5, and I have an IF statement in the below program
> that does not seem
> to be doing it's job. The program simply acquires a range of years from
> the user and prints out
> all the leap years between the two dates. I am having trouble in
> trapping for possible user
> errors. I am using x.isalnum() to check that I have a number for each
> year entered, and it
> doesn't look to me like it is functioning properly.
>
> When I purposely enter bad data, such as 'aaaa' for one of the a year
> entries, the IF statement:
>
> if start.isalnum() == 1 and end.isalnum() == 1:
>
> -Fails to detect that 'aaaa' is not a number and lets the program then
> die tragically a horrible
> sudden awkward death on the very next line:
>
> start = int(start); end = int(end)
>
> Traceback (most recent call last):
> File "/home/lucky/Documents/Python_Programs/leap_years.py", line 119,
> in <module>
> start = int(start); end = int(end)
> ValueError: invalid literal for int() with base 10: 'aaaa'
>
> If I say on the commandline:
>
>>>> n = 'aaaa'
>>>> n.isalnum()
> True <------------It seems to me it should be saying
> False!!!
>>>>
>
>
> My program starts here:
>
> def leap(yyyy):
> answer = 0
> t1 = yyyy / 4
> if t1 == int(t1):
> t2 = yyyy / 100
> t3 = yyyy / 400
> if t2 <> int(t2) or t3 == int(t3):
> answer = "-- leap year!"
> return answer
>
> print "This program finds all leap years between two dates.";print;print
>
> start = raw_input("Enter yyyy for beginning year : ")
> end = raw_input("Enter yyyy for ending year : ")
>
> if len(start) == 4 and len(end) == 4:
> 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:
> print; print
> for i in range(start, end + 1):
> answer = leap(i)
> if answer != 0:
> print i, answer
> print "Done!"
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list