1

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?

Jon-Eric
  • 16,977
  • 9
  • 65
  • 97
Aperture
  • 13
  • 5
  • Isnt the right way of doing this to find if there was a reminder or not ? - Yes, I am talking about the `%` operation. – Jeffrey Jose May 30 '10 at 19:22

4 Answers4

2

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
Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
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.

Jon-Eric
  • 16,977
  • 9
  • 65
  • 97
0
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
  • 278,309
  • 50
  • 514
  • 539
0

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,495
  • 16
  • 20