tags:

views:

121

answers:

4

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 catch if it's an int or a float before doing other things in my program?

A: 
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).

Matthew Flaschen
A: 

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.

Josh Wright
+2  A: 

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
The MYYN
Thank you, very much.
Aperture
+1  A: 

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.

Jon-Eric