Cooking with Python by Robin Parma, Alex Martelli, Scott David
Daniels, Ben Wolfson, Nick Perkins, Anurag Uniya, Tim Keating,
Rael Dornfest and Jeremy Hylton, authors of the Python Cookbook
1. Simple Tests Using Exceptions Usually Python is
straightforward, but there are a few unexpected exceptions.
Credits: Robin Parma You want to know if the contents of a
string represent an integer, which is not quite the same thing
as checking whether the string contains only digits. #
try/except is generally the best approach to such problems: def
IsInt(str): """Is the given string an integer?""" try:int(str)
except ValueError:return 0 else:return 1 Use exceptions to
perform simple tests that are otherwise laborious. If you want
to know if the contents of a string represent an integer, just
try to convert it. That's what IsInt() does. The try/except
mechanism catches the exception raised when the string cannot be
converted to an int, turning it into a harmless return 0. The
else clause, which runs only when no exception