'20' <= 100

Dave Brueck dave at pythonapocrypha.com
Thu May 1 19:57:32 EDT 2003


On Thu, 1 May 2003, HP wrote:

> I have a statement somewhere in the code that
> boils down to comparing a string object with an integer.
> i.e.  var1 <= var2
> where var1 = '20' and var2 = 100
>
> The code runs ok but the above comparison always return 0 !!
>
> It took me quite an effort to finally pin it down.
>
> Is it the programmer's responsibility to check the
> type of var1 and var2 before using <=   ???

No, but it _is_ the programmer's responsibility to understand that data
that's being processed. :)

There's no way for Python to magically guess it for you - the bug in your
program isn't that you didn't check the type but that you're not operating
on the type of data you think you're operating on (it's a slightly
higher-level bug).

Put another way, if you give Python:

s = '20'
t = 2
x = s * t

How can it know that you expected 40 instead of '2020'?

-Dave





More information about the Python-list mailing list