Practice Makes Perfect 3/15: is int. Is this code valid or cheating?


#1

Hello!

I am at https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isint?action=lesson_resume

I have passed the exercise already, but I have seen so many solutions to it in the forum that I´d like to know whether my code is working or just cheating the system, but also if it is the right approach to solving this type of problems or I am just not getting what Python is about. My code is as follows:

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

Is my code worse than, say, the following one? (from here, which I like a lot)

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

Also, I have seen people using modulo, as in

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

Which I assume is a “better” way, as it is less lines and therefore seems more efficient. Nevertheless, I don´t get how it works here: why the if/else True/False statements are not needed when modulo is used?

Sorry for a rather dull question: I am trying to learn what sort of coding is considered “the right way”, besides it plainly working or not.

Thanks a lot for your patience!


#2

In truth, the modulo has nothing to do with it. It’s the boolean expression that is being returned. Expressions are evaluated immediately so either True or False are returned.

    return x - int(x) == 0

although as I recall, int() is off the table.

We can alsp return a logical expression …

    return not x % 1

In the above, not converts the expression that follows it to a boolean and then negates it (toggles).

not 1.1 % 1  ->  not 0.1  ->  not True   =>  False

not 3 % 1    ->  not 0    ->  not False  =>  True

#3

Hello!

Thanks for the answer! However, you got me a little lost with the following:

Shouldn´t it be

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

?

Otherwise, I do not really understand why the “==0” in the return expression, if the result of the operation return x - int(x) might not be 0.

The not option I get it.

If you could give me any opinion on the code I used, to see if it´s too cumbersome for the task or not, that would also be great :slight_smile:

Thanks in any case!


#4

When the expression yields a boolean, we don’t need an if statement, just a return.

>>> x = 1.23
>>> x - int(x) == 0    # boolean expression
False
>>> x = 3
>>> x - int(x) == 0
True
>>> 

#5

Got it now!

Thanks a lot!


#6

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