Reputation: 11
My task is to write a function named only_ints
that takes two parameters. Your function should return True
if both parameters are integers, and False
otherwise.
For example, calling only_ints(1, 2)
should return True
, while calling only_ints("a", 1)
should return False
.
I'm confused. How do I apply type()
? Because isinstance(False, int)
outputs --> True
Upvotes: 0
Views: 1054
Reputation: 1480
You can use type
and ==
. isinstance sadly does not behave intuitively in this situation.
def only_ints(x,y):
return type(x) == int and type(y) == int
Upvotes: 0
Reputation: 405735
You could use ==
to compare the type
of a variable or value to a known type.
>>> type(True) == int
False
>>> type(3) == int
True
Before you implement only_ints
using type
, you should verify that you don't want True
and False
to be considered int. Booleans do evaluate to integer values in Python in many contexts.
Upvotes: 0
Reputation: 23815
isinstance
is the right tool to be used here. bool
is a private case of int
and therefore we give him a special care :-)
Try (print(True + 1)
) and see that the result is 2
def only_ints(x: int, y:int) -> bool:
return isinstance(x, int) and not isinstance(x, bool) and isinstance(y, int) and not isinstance(y, bool)
print(only_ints(4, 6))
print(only_ints(4, False))
output
True
False
Upvotes: 1