I have just started OOPs in python and came across this piece of code . I was trying to understand the code in https://pythontutor.com/render.html#mode=display but could not understand the output of first if statement , if float value is passed(like the code). Secondly , during visualizing the code in the mentioned link , third statement is skipped , cannot understand why ? It will really be helpful if someone , can that I am unable to understand .
class CheckValue:
@staticmethod
def is_integer(num):
if isinstance(num, float):
return num.is_integer()
elif isinstance(num, int):
return True
else:
return False
val = CheckValue.is_integer(10.5)
print(val)
CodePudding user response:
10.5
is a float, so isinstance(num, float)
will be true, and the first if
block is executed.
The float.is_integer()
method tells whether the float is equivalent to an integer, i.e. it has a .0
fraction. Since 10.5
doesn't have a zero fraction, num.is_integer()
returns False
, and that's returned by the function.
If you were to call CheckValue.is_integer(10)
, the first if
condition would fail, because 10
is an int
, not a float
. The the next condition, isinstance(num, int)
, would be tested. This will be true, so return True
will be executed.
Finally, if neither of these conditions is true, the else:
block is executed and the function returns False
. You can see this if you call it with a non-numeric argument, CheckValue.is_integer("123")
. "123"
is a string
, so neither of the isinstance()
calls will be true.
CodePudding user response:
def is_integer(num):
# If num is of type `float` (i.e. a decimal number)...
if isinstance(num, float):
# use the member function of `float`s to determine whether
# it's an integer or not, and return that value.
return num.is_integer()
# Else, if num is of type `int`...
elif isinstance(num, int):
# ...just return true because `int`s are always integers
return True
# In any other case (for example if you pass a
# letter instead of a number)
else:
# return false, as only integers are integers.
return False