Is_int


#1

Hello,

An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not).

For the purpose of this lesson, we’ll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0.

This means that, for this lesson, you can’t just test the input to see if it’s of type int.

If the difference between a number and that same number rounded is greater than zero, what does that say about that particular number?

For the above exercise, Below is my code

def is_int(x):
if x == round(x):
return True
else:
return False
------------------------------------------------------------------------But the actual code by Codeacademy is

def is_int(x):
absolute = abs(x)
rounded = round(absolute)
return absolute - rounded == 0

My question is what is difference between my code and codeacademy code. Can someone please help me to understand. Thanks.


#2

See here in your code lets take x=10 then round(x) = 10.0
if 10 == 10.0 is not true


#3

CC’s use of abs is redundant, after that you’re doing the same thing. Note how they’re returning the result of the comparison instead of using an if-statement though - there’s no need to test if something is true and then return true… just return the result directly.


#4

Thank you. Can you suggest on the below revised code. Appreciate your response

def is_int(x):
return x == round(x)


#5

Don’t know what you mean, but yes, that is, aside from broken formatting, what you end up with if you start removing all the things that don’t do anything.


#7

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