Is_int


#1



Can someone explain why my code is wrong??
I know its long but it sure does work right?
Thnx!


 
def is_int(x):
    if x>0:
        if x-(round(x))>0:
            return True
        else:
            return False
    else:
        if x-(round(x))>0:
            return False
        else:
            return True
print is_int(-87.88)


#2

round() is not always the floor value, but could go up as well. It's called the 5/4 rule. Up on 5, down on 4.

The simplest way to confirm an integer, or at least a float with no decimal fraction, is to use the modulo operator and 1

if x % 1 != 0: return False

#7

Don't use two `elses its better to use elif. This probably isn't going to help


#8

The use of nested if's is alright. However the OP code is complicated, repetitive and can give false positives.

Consider,

    if x>0:
        # code
    else:
        # code

Is it necessary to check the sign on a number to determine if it is an integer? Answer: No, it is not. The sign has no bearing on an integer (or float with .0)

Now consider this code:

        if x-(round(x))>0:
            return True
        else:
            return False

Let x = 11.5 so that round(x) = 12. The above returns False, which is true.

Let x = 11.4 so that round(x) = 11. The above returns True, which is a false positive.

However, just this structure is enough code to do the job once we sort out the false positive. We don't need a huge structure, especially given that both main cases contain exact same code.

return False if x - round(x) != 0 else True

Now it doesn't matter if rounding is up or down.

As indicated in the earflier post, we don't need a function in this evaluation since we can use the modulo operator.

return x % 1 == 0

More particularly, if we wish to trap illegal inputs:

def is_int(n):
    try:
        return n % 1 == 0
    except:
        return "Type Error"

Numbers will pass the try expression, non-numbers will fail, and follow the exception branch.


#10

what if i enter a string? how can python see the difference?


#11

Python will raise an exception if we try to perfom a math operation on a non-number. We trap that with the except branch and prevent a fatal error from occuring.