[Tutor] n.isalnum() is failing
Terry
terry.kemmerer at gmail.com
Tue Jul 3 09:51:31 CEST 2007
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!"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070703/fa81e8f8/attachment.htm
More information about the Tutor
mailing list