3/15 is_int (looking for help)


#1



hi guys , i don't hunderstand why my code is not working , please , explain to me why is it not working and how i could improve it

thanks guys !


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


#2

I will suggest you to read instruction to this task once again.

I think, that this part is quite important: "If the difference between a number and that same number rounded down is greater than zero, what does that say about that particular number?"

It also helped me to check what exactly int() does to a float number

y = 4.7
print y
print int(y)

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

This worked for me. My question is, is this what code academy wants? Or is this cheating the system?


#4

Hi @kefferrhodes,

I think this code is actually okay :slight_smile: Since by doing this you are not directly testing the type of input to see if it is an integer. Rather, you are comparing the input x and the integer version and checking if there is a mathematical difference between the 2, which would make something like 7.0 return true as well (as wanted by codecademy) although conventionally speaking it is a float.

Alternatively, if you want to avoid having the int() appear altogether, you can consider something like this:

def is_int(x):
    if x - (x // 1) == 0:
        return True
    else:
        return False

Hope this helps :slight_smile:


#5

I think what your code is saying when 7.5 is called is: If 7.5(when called) is equal to 7 return true or false, which in this case is false. In this way it manages to trick the compiler because it expects a false answer for 7.5 when called. I do however think its a very smart code because 7.0 and 7 are actually equal. I like @umopapsidn code only that i have not seen the method covered.
Here is my code just incase:
def is_int(x):

if int(x) - x <= 0 and int(x) - x >= 0:
    return True
else:
    return False

#6

Hi @tonypeaks,

Glad you found something useful in my code. Thanks for sharing your code too, but I find this bit puzzling:

if int(x) - x <= 0 and int(x) - x >= 0:

Thinking carefully, I realise that this is a condition which can only be fulfilled when int(x) - x == 0 (because you used an and operator). So I don't think your code is any different really from @kefferrhodes :stuck_out_tongue:


#7

Hi @umopapsidn, come to think of it, you make a good point, the difference is in how we approached it which i have to admit opens my mind to the different ways of solving a problem. A look at your code follows the same template really, that for the code to run as true it must be equal to 0.


#8

Guys, you could just use modulo:

def is_int(x):
    return x % 1 == 0

This works because the function asserts that the number (x) divided by 1 has no remainder; think of integers as multiples of 1.