Why does this code work for the "Is_Int" section


#1

Hi,

I was doing the Is_Int section on Practice Makes Perfect, and from what I read from the instructions, I submitted:

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

Later on I found out that the more appropriate code probably is:

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

Now the question I have is, can anyone help explain to me why the first set of code would still be consider correct by Codeacademy(both are when I submit them)?

I checked and the int() function is suppose to convert strings and variables to integers. Whereas the round function actually rounds the numbers in the function, which would be more useful in this situation.

Any help would be appreciated.


#2

Well...Tracing from those codes, you are correct with the int() function. It changes any type (be it float, string, etc.) to integers which are positive whole numbers. Think of it as simply removing any number after the decimal. So int(7.9) = 7.
In the first code, if you have a float, 7.5,

7.5 - int(7.5) != 0 # where int(7.5) = 7

so 7.5 is not an integer.
If you have 6,

6 - int(6) = 0 # where int(6) = 6

so 6 is an integer.
In the second code, the round() function rounds numbers up or down. Let's say you have 7.5 again.

7.5 - round(7.5) != 0 # where round(7.5) = 8

so 7.5 is not an integer.
If you have 6,

6 - round(6) = 0 # where round(6) = 6

so 6 is an integer.
In this case, it doesn't matter if you use int() or round() because the results they produce are not too important as long as they both produce an integer.


#3

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