if fhhf
if fhhf

Reputation: 119

how to make a distinction for float vs integer (after some computation) for conditional statement?

I have some integers x,y,z ; and let's say that I am doing a = (x+y)/z.

And I want to write some code if a is an integer, and some other code if a is a float (not a whole number).

How can I do this? Because as far as I understand, after doing the above computation, a will automatically become a float- so how can I write a condition to make this distinction?

Upvotes: 1

Views: 56

Answers (1)

Guy
Guy

Reputation: 50899

You can use float.is_integer()

a = 2.0
print(a.is_integer()) # True

a = 2.5
print(a.is_integer()) # False

Another option is to check if a is equals to int(a), the casting will round down the float to the closest int

a = 2.0
print(a == int(a)) # True

a = 2.5
print(a == int(a)) # False

Upvotes: 3

Related Questions