Reputation: 272
I am a complete beginner in Python... Currently I am trying to write a function which first checks whether the inputs x and y are int or float.
My guess which does the job is
if (type(x) != int and type(x) != float) or (type(y) != int and type(y) != float):
However, this seems quite clumsy / inefficient to me and will be difficult to generalise in case of many inputs. Therefore I think there should be a more elegant way to write this condition..? Thank you for any ideas!
Upvotes: 0
Views: 632
Reputation: 34046
Use isinstance
:
if not isinstance(x, (int, float)) and not isinstance(y, (int, float)):
# do something..
Upvotes: 1
Reputation: 46849
probably the most general way is to use a base class from the numbers
module:
from numbers import Number
if isinstance(3.3, Number):
...
small caveat: this will also accept complex numbers (e.g. 2 + 4j
). if you want to avoid that:
from numbers import Real, Integral
if isinstance(3.3, (Real, Integral)):
...
Upvotes: 0
Reputation: 23815
use isinstance
- see code example below
https://www.programiz.com/python-programming/methods/built-in/isinstance
def foo(x, y):
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
print('great input')
else:
print('wrong input')
Upvotes: 0
Reputation: 54148
Use isinstance
if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
Upvotes: 1