Is_int


#1

Define a function is_int that takes a number x as an input.Have it return True if the number is an integer (as defined above) and False otherwise.def is_int(x

This is my code:

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

is_int(7.9)

I don´t know what is wrong , but it doesn´t work, the error says:Oops, try again.
Your function fails on is_int(-2). It returns False when it should return True.


#2

You are yet to even write the function in the question. Please, see hint below.

def : #function
    if :  #your condition goes here
        return True
    else:
        return False

#3

Hi,

Don't worry about what you have done so far. As per the course, go through the instructions where it says:

FIRST: Define a function for which use the "def" to assing as it reads in it.

SECOND: If you have forgotten how to check for an integer number. Here is the hint: use the "type" function to do that. Or, to be more precise, something like type(whatever) == whatever.

Third: Make a else: and return false to it.

Try this and keep me updated. I'll guide you further if you needed to be so. :slight_smile:


#4

try -> abs(x-round(x))>0


#5

Why do you guys complicate?

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


#6

that's a good shot.
to become a good coder, you have to be good at math first. LOL


#7

I honestly thought that if we use int() that it would only work for eg 7 but not for 7.0 as 7.0 is seen as a float?


#8

If you type:

(1.0).is_integer()

You will see if the number is an integer. 1.0 will return as True. That's because this number is a whole number represented as a float. You could call your is_int() function like this:

print(is_int(1.0))

This would return as True. You could add any number you'd like there and you should get the correct result.

To be more explicit, say you wanted to go a little further and have the user input a number to figure out if the number was whole or not. Your code would look something like this:

def is_int(x):
    if x == int(x):
        return True
    else:
        return False
        
x = float(input("Please enter a number: "))
print(is_int(x))

You would add the float function to the input (on newer versions of Python, at least as far as I can tell) because you want the user to be able to write in floating point numbers and check to see if they are whole numbers, which is part of what the int() function does.

Therefore, 1 is the same as 1.0 because 1.0 is a whole number and that's how int() will consider it to be when that argument is passed to it.

I hope this makes sense :stuck_out_tongue:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.