Solve this problem using knowledge we have acquired so far


If we are only supposed to solve this problem using knowledge we have acquired so far till this exercise than here is a way I have solved it.

def is_int(x):
    #store the number as string in variable 'numb'
    numb = str(x)
    #split the converted numbers at '.'
    #store the results in the list
    rounddownlist = numb.split('.')
    #The first element in the list above would be our rounded down number
    #However, we need to convert the rounded down number back to number using int()
    rounddown = int(rounddownlist[0])
    #Use of 'abs' below avoids errors with negative numbers
    #sample error
    #Oops, try again. Your function fails on is_int(-3.4). It returns True when it should return False.
    if (abs(x) - abs(rounddown)) > 0:
        return False
        return True

num1 = -1.0
num2 = 6.3
num3 = 5
num4 = 100.0
num5 = -4.4

print is_int(num1)
print is_int(num2)
print is_int(num3)
print is_int(num4)
print is_int(num5)


Okay so this turned out to be a lot. It's not meant to say that you did a bad job, you did a great job figuring out a way to identify an integer. Still, there's much to improve here, I'm happy if you can make use of just a single thing I mention here:

If you've got a collection of numbers you might not want to use a variable for each one (num1 num2 num..5) - a list would be more manageable:

nums = [-1.0, 6.3, 5, 100.0, -4.4]
for num in nums:
    print '{}: {}'.format(num, is_int(num))

The formatting there could also have been written as:

'%s: %s' % (num, is_int(num))

(%s means to use default string conversion which is fine unless you want something other than that)

but the former method is preferred

And then this:

if (abs(x) - abs(rounddown)) > 0:
    return False
    return True

Could have been written as:

return abs(x) - abs(rounddown) == 0


return abs(x - rounddown) == 0


return x - rounddown == 0


return x == rounddown

And if you do int(-1.5) then that will not round down - it truncates towards zero, the result of that is -1 which makes your rounddown name misleading! It works out correctly but it certainly doesn't help in reasoning about its correctness.

And since int already truncates, your whole function boils down to:

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

Which also happens to be really easy to look at and say: "Yeah, that's correct"

Or, if going by the string/split method, it could be tested that the right side is only zeros.

Yet another method is to divide by 1, or to do modulo 1 and look at the remainder.


Thank you for your time and input! It make sense. I will try to make use of it in next exercises.