0

I want check a type of a number in python, for example

x=4
y=2
type(x/y) == type(int)
--> False

it has to be True but what python makes is, it takes 4/2 as 2.0.

2.0 is a floating number, how can I make 2.0 to 2 but at the same time I don't want to make 2.5 to 2 for example :

x=5
y=2
type(x/y) == type(int)
--> False

This is what I want. In conclusion I need something that can understand if a number is int or a floating number after a division operation. Can you help me please

4
  • I think you want what is explained in this answer: stackoverflow.com/questions/4541155/… Commented Mar 6, 2017 at 19:58
  • 1
    What's preventing you from writing a function that does just that? Commented Mar 6, 2017 at 19:58
  • but your problem here is that type(int) returns <type 'type'> not <type 'int'> Commented Mar 6, 2017 at 19:59
  • Having the result's type depend on the value is usually a bad idea. If you want to perform a divisibility test, there's a much better way to do that: x % y == 0 if x is divisible by y. Commented Mar 6, 2017 at 20:10

2 Answers 2

1

The output of / is going to be a float. You can define your own function that wraps /

import math
def my_div(a, b):
    x = a/b
    if math.floor(x) == x:
        return int(x)
    return x
Sign up to request clarification or add additional context in comments.

2 Comments

return a//b if a//b == a/b else a/b is equivalent
@TemporalWolf and probably unreadable for someone who doesn't grok the difference between a float and an int
1

In python 3, x/y will always be of type float, so forget about type

If you only have int numbers as input you could just use modulo:

x%y == 0

yields True if the result is integer, False otherwise

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.