[Tutor] Out of range
Magnus Lycka
magnus@thinkware.se
Wed Feb 5 09:10:02 2003
At 09:49 2003-02-05 -03-30, Adam Vardy wrote:
>Which conversions were they?
Two functions called sci2float and float2sci.
>If I sort just some plain numbers, I am
>still left with some unsorted lines of text.
>>> i = 5
>>> type(i)
<type 'int'>
>>> s = '5'
>>> type(s)
<type 'str'>
Just because a string only contains digits doesn't mean that
it becomes a number in Python. Some languages behave in that
way, and it can cause a lot of problems. In python you must
explicitly tell the computer to extract a number from a string
if you want that.
>>> s = '5'
>>> i = int(s)
>>> print i, type(i)
5 <type 'int'>
>>> f = float(s)
>>> print f, type(f)
5.0 <type 'float'>
In a few selected cases, Python will actually perform an implicit
type conversion. For instance, you don't have to do
a = 5
b = 6.3
print float(a) + b
Python will automatically coerce a float and an integer on addition,
so you can just type
a = 5
b = 6.3
print a + b
and get the float 11.3 as result, but you can never do
print 5 + '6.3'
Python will refuse to convert strings to numbers implicitly.
In some languages, OCaml for instance, you must explicitly convert
an integer to a float if you want to add it to another float. This
is partly a tradeoff between convenience and performance. It's also
an issue of avoiding bugs. I think Python strikes the right balance.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se