How does compare work?
Josiah Carlson
jcarlson at nospam.uci.edu
Tue Jan 27 17:30:04 EST 2004
> But silently(!) comparing apples with pears is evil. E.g. the example I
> came across this was
>
> thresh=raw_input('enter threshold')
> ...
> level=2
> ...
> if level > thresh :
>
> which failed miserably. By the way, Perl does convert the string to an
> integer silenty and, as most of the time, these Perl conversions are
> just what one wants, so here.
> Nevertheless, I'd prefer an exception in this case since automatic
> conversions can never be right in all circumstances.
> So this is a case where Python is a very dangerous language!
The comparison doesn't fail, it succeeds, just not the way you like. If
you want thresh to be an integer, perhaps you should say
thresh = int(raw_input('enter threshold'))
Perhaps one way to alleviate the problem is to have a special kind of
input function:
def special_input(prompt, typ):
a = None
while a is None:
if typ is int:
r = '-?[0-9]+'
#special cases for each kind of input
a = re.search(r, raw_input(prompt))
if a is not None:
return typ(a.group(0))
Maybe a more fully featured set of input functions would be useful to
include in the standard library. Perhaps someone should write an
example module and submit it.
- Josiah
More information about the Python-list
mailing list