[Tutor] python help

boB Stepp robertvstepp at gmail.com
Sat Sep 12 18:04:06 EDT 2020


On Sat, Sep 12, 2020 at 09:46:53PM +0100, Alan Gauld via Tutor wrote:
>On 12/09/2020 18:56, John Weller wrote:
>
>> ...the way to check if a number is an integer is:
>>
>> If number == int(number):
>> 	Print("Integer")
>> Else:
>> 	Print("Not integer")
>
>Sorry, tat won;t work. int() will throw an exception if it can't convert
>the argument so it needs to be:
>
>try: int(...)
>except ValueError: ...

And to further enhance Alan's point, this eliminates floats presented as
strings when you really only want integers and not floats:

3.8.3:  int("1.0")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   ValueError: invalid literal for int() with base 10: '1.0'

If I recall correctly when I first discovered the Tutor list I asked the
question why "int('1.0')" did *not* convert it to the integer "1", but
instead threw an exception.  It occurs now to me how useful the Python
design has proved to be for me!

-- 
Wishing you only the best,

boB Stepp


More information about the Tutor mailing list