Problems using struct pack/unpack in files, and reading them.

Chris Angelico rosuav at gmail.com
Mon Nov 16 08:27:55 EST 2015


On Tue, Nov 17, 2015 at 12:17 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 15 Nov 2015 01:23 pm, Chris Angelico wrote:
>
>> On Sun, Nov 15, 2015 at 1:08 PM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>>> number = +raw_input("enter a number: ")
>>>
>>> versus:
>>>
>>> text = raw_input("enter a number: ")
>>> try:
>>>     number = float(text)
>>> except ValueError:
>>>     number = int(text)
>>
>> What kinds of strings can float() not handle but int() can,
>
> Heh, I think I got the order of them backwards. You should try to convert to
> int first, and if that fails, try float.

Ah! Yes, that makes sense then. I assumed this...

>> and in a
>> program that's going to group floats and ints together as "numbers",
>> will they ever be useful? I'd be more likely to write this as simply:

... on the basis of the "float first" check.

> Obviously this code assumes you want to distinguish between ints and floats
> for some reason. In Python, unlike Lua, Javascript and a few others, we do
> distinguish between ints and floats. Since they have different
> capabilities, that may sometimes be useful:
>
>
> py> 10.0 ** 400
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> OverflowError: (34, 'Numerical result out of range')
> py> 10 ** 400
> 1000000000000000000000000000000000000000000000000000000000000000000000000
> 0000000000000000000000000000000000000000000000000000000000000000000000000
> 0000000000000000000000000000000000000000000000000000000000000000000000000
> 0000000000000000000000000000000000000000000000000000000000000000000000000
> 0000000000000000000000000000000000000000000000000000000000000000000000000
> 000000000000000000000000000000000000

Right. If you check int() first and then float(), you can make use of
this. But if the user enters that string and you try to float() it, it
will work:

>>> float(str(int(10**400)))
inf

Hence my confusion. :)

With that small change, your code makes fine sense.

ChrisA



More information about the Python-list mailing list