Something that's a float
is not an int
. They're separate types. You can have a float
that represents an integral value, like 1.0
, but it's still a float
.
(Also, user_input == int
isn't checking whether user_input
is an int
, it's checking whether user_input
is actually the type int
; you wanted isinstance(user_input, int)
. But since that still won't work, let's skim over this part…)
So, can you check that a float
has an integral value? Well, you can do this:
if int(user_input) == user_input
Why? Because 1.0
and 1
are equal, even though they're not the same type, while 1.1
and 1
are not equal. So, truncating a float
to an int
changes the value into something not-equal if it's not an integral value.
But there's a problem with this. float
is inherently a lossy type. For example, 10000000000000000.1
is equal to 10000000000000000
(on any platform with IEEE-854 double as the float
type, which is almost all platforms), because a float
can't handle enough precision to distinguish between the two. So, assuming you want to disallow the first one, you have to do it before you convert to float
.
How can you do that? The easiest way to check whether something is possible in Python is to try
it. You can get the user input as a string by calling raw_input
instead of input
, and you can try to convert it to an int
with the int
function. so:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
If you need to ultimately convert the input to a float
, you can always do that after converting it to an int
:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
else:
user_input = float(user_input)