Numbers in scientific notation should not be cast

I have recently updated to Python 3.11 from 3.8 and started getting warnings about randrange() only accepting integers as inputs. I thought I was only using integers with the randrange() but I realised that by using scientific notation I always get floats even though I specify integer numbers (e.g., 1e6).

I have no issue with randrange() accepting only integers – it makes sense – but scientific notation is mainly meant for convenience and therefore having to write “int(1e6)” to get integers is not helpful. One might as well write 1000000. So why are numbers in scientific notation type-cast?

(I have noticed that some would want int() to accept scientific notation strings but that is not my issue)

Obviously, this is not a huge problem, simply annoying, and so I was wondering: what was the reasoning behind the decision to assume all numbers in scientific notation are floats? Is there a PEP for this? Could this be changed in the future?

1 Like

They’re not type-cast; it’s simply that exponential form is a feature of float literals, not integers.

You can write 1_000_000 for one million, or you can write 10**6, and both of those will be integers.

For large numbers (much larger than 1e6), this will not give the expected/intended result (because of the inherent imprecision of floats):

>>> 10**23
100000000000000000000000
>>> int(1e23)
99999999999999991611392

Of course, such large numbers are unlikely for randrange(). But from a principled view, I recommend using @Rosuav’s suggestions that avoid this issue.

Yep, plus that’s not a literal any more - this actually is a type cast. (Technically 10**23 isn’t a literal either, but thanks to constant folding, it behaves like one - it’s as fast and reliable as a literal.)

Thank you for the comments and recommendations. I was unaware of these differences.

Read 2. Lexical analysis — Python 3.11.3 documentation or even the whole chapter to master python.