How can I test if a number is an integer without using type( )?


#1

Question

How can I test if a number is an integer without using type( )?

Answer

The instructions want us to not use the built in type() function to determine if the given number x is an integer or not. To do this, we’ll need to round the value given to us, and we can do that using one of two functions: ceil() or floor(), which are both available through the math module we learned about earlier.
We can do this because if we round a number and it’s different than our initial number, we know the number given was a float. For example, if we’re given 78.6 and we round it, we’ll have 79. The difference between the two is not 0, so we know we were given a float!


FAQ: Learn Python - Practice Makes Perfect - is_int
#2

Way without using additional modules.

def is_int(x):
  print x
  print int(x)
  if x==0:
    return True
  elif (x/int(x))==1:
    return True
  else:
    return False

#3

I totally forgot about those functions in the math module, So I just simply compared the x to what x would be if it’s an integer using int(x). If it doesn’t match then its a float or something else

def is_int(x):
  if x == int(x):
    return True
  else:
    return False

#4

I used modulo (which was in the previous lesson) - if it can be divided by 1 without a remainder, then it’s an integer ??:
def is_int(x):
if x % 1 == 0:
return True
else:
return False