15.3 is_int()


#1

Most answers I saw here used somekind of function. So I don´t know if the way I did is better or worse. Is it bad to do things like this?

def is_int(x):
if x > 0:
    while x >= 1:
        x -= 1
    else:
        if x == 0:
            return True
        else: 
            return False
elif x < 0:
    while x <= - 1:
        x += 1
    else:
        if x == 0:
            return True
        else:
            return False
else:
    if x == 0:
        return True
    else:
        return False

#2

Instead of

if x == 0:
    return True
else:
    return False

do:

 return x == 0

You say that you don't use functions, but you do! Lots of them!
Every single operator is a function (+ - * / == -= etc..), it's just that the syntax is a little different. Some arguments go in, and a result comes out. They are functions.

You'll run into trouble for large numbers, and if it isn't a number, then the value might not support the operations that you attempt and the function would crash.

If I were asked to do this I would write:

def is_int(x):
    return isinstance(x, int)

And I realize that floats like 5.0 are intended to be considered ints here but I certainly do not, because why then was it converted to float in the first place? floats are approximations of numbers and it's a bad idea to ever consider them exact.

Testing if a float is equal to something == is also an exact operation. "Almost equal" might not be "equal" - but floats don't represent "exactly equal" so "almost equal" is actually the only thing that makes sense.

Floats are approximations of numbers and for any other purpose you should stay clear of them, there will be something more appropriate to use.

The exercise is misleading and should really be about how you shouldn't use floats if you can avoid it. (Or that's my 2 cents anyway)

Most of the time it'll work just fine to treat floats as if they were exact. That only makes it more dangerous, because the bug may stay around for a long time because of how it only occurs once in a blue moon, or perhaps it starts occurring very often, but only after something else has changed.

Here's an example of what can happen:

(0.1 + 0.2) * 10 == 3

This evaluates to False
The left side is an approximation of 3, but it isn't equal to 3