Alex Alex - 1 month ago 9
Python Question

How to test if a number is an integer or a float that only has a zero after the decimal?

Just to clarify, I am Using Python 2.7

I need to check if "x" is an integer (for example 7) or if "x" is a float with only a zero at the end of the decimal (for example 7.0). I have a format so all I need help on is the code.

x = raw_input("Please enter a number: ")

if type(x) == int or __________ :
return True
else:
return False


My goal is if you plug in a 5 or 5.0, it will return True, but is you plug in a 6.7, it will return False.

The underscores (empty spaces) are where I need to add the code. I tried many different attempts at this but they all failed.

Answer Source

A very simple test, which works because Python integers are unlimited in resolution:

return float(x) == int(float(x))

The result from raw_input isn't a number, it's a string. That's why it has to be converted to float first.