I am following this tutorial video from freeCodeCamp called Object Oriented Programming with Python. That tutorial, or object oriented programming isn’t necessarily important to this topic. But in that tutorial there is a function that I still don’t understand why it works. Hopefully someone here can explain it in a way I understand.
def is_integer(num): # check if num is an integer. # Floats ending with point-zero are considered integers. if isinstance(num, float): return num.is_integer() elif isinstance(num, int): return True else: return False
If you run the code yourself, you will see that it works as expected. Inputs of
True while an input of
False. But I don’t understand how this works. Even after stepping-through with the debugger, I don’t understand how this can possibly work. I am confused by the line
- How is it that
num.is_integer()does not result in an error when
is_integer()is not a method of the float class?
- How does this return True for input of
From what I understand that return statement should cause an infinite loop. to me it says “is num a float? Yes, then return the output of this function with this number. Is num a float? Yes…”
I understand how numbers like
isinstance(num, float) to return True. I have no idea how then
return num.is_integer() somehow differentiates between