-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Consider using something like:
try:
start, end = int(start), int(end)
except ValueError:
print "oops it was not a number."
Andreas
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 - [email protected]
> http://mail.python.org/mailman/listinfo/tutor
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFGij4jHJdudm4KnO0RAnKcAJ4lQWC3g0RklnwDwbpldapIeGFxDwCg2ayR
Mr6uMnoXINQHF3QTLO6Rl34=
=0kzm
-----END PGP SIGNATURE-----
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor