3. is_int HELP!


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/3?curriculum_id=4f89dab3d788890003000096

My code keeps throwing the following error: "Your function fails on is_int(-2). It returns False when it should return True."

Here's my code:


def is_int(x):
    if type(x) is int and (x-x) > 0:
        return True
    else:
        return False


I've been stuck on this lesson a LONG time and I've looked all over the web and have found nothing that's been super useful. please help =(


#2

the first problem is this line:

(x-x) > 0

if you have a negative number, -2--2 = 0, so this condition is false. it should be (x - x)>= 0

Also, this programs wants 7.0 to return true, which type(x) is int doesn't. You can use the modulo operator:

x % 1 == 0

if the number is a integer (or a float with a zero behind the decimal), this condition will be true


#3

HI,

I think the easier part of your question is the (x - x) > 0. For all the integers, (x - x) == 0, which makes the logical result of the (x - x) > 0 will be False. And with an "and" logical judgement, the whole if statement will result in False only.

The trickier part is the type(x). The type() will return an integer data type. However, the is_int() want to check whether a number is a integer. Hence, you may not use the type(x) is int as a shortcut.
e.g. for 5.0, the type is float, but the number is an integer.

Hope this may answer your question.


#4

A post was split to a new topic: Don't understand why it's wrong


#5

the problem is in line 2, the if
this works
x == int(x)


#6

Thank you! it worked =D


#8