开发者

Python making sure x is an int, and not a pesky float

开发者 https://www.devze.com 2023-01-01 07:57 出处:网络
For example: import random x = random.randint(1, 6) y = 2 new = x / y ... now, lets say x turns out to be 5.

For example:

import random
x = random.randint(1, 6)
y = 2
new = x / y
...

now, lets say x turns out to be 5. How can I ca开发者_StackOverflowtch if it's an int or a float before doing other things in my program?


By default, integer division works a little unexpected in python 2, if you don't

from __future__ import division

Example:

>>> 5 / 3
1
>>> isinstance(5 / 3, int)
True

Explanation: Why doesn’t this division work in python?

Finally, you can always convert numbers to int:

>>> from __future__ import division
>>> int(5/3)
1


If you want want new to always be an int, one option is floor division:

new = x // y

Another is to round:

new = int(round(x/y))

If instead, you just wanted to check if new is a float, that's a little unusual in Python (usually, type-checking isn't necessary). If so, tell us more about why you want to check and you'll get better guidance.


isinstance(x, int)

But it's rare you need to do this. Double-checking the standard library is probably not one of those times. :)

Note that you can also catch exceptions in some cases (though that wouldn't apply to this example).


If you don't mind the value being truncated (5.7 would become 5), you can simply cast it to an int.

must_be_an_int = int(x)

If for some reason x is something that python can't convert to an int, it will raise a ValueError exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消