0

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!

2
  • Use isinstance(). Commented Nov 8, 2020 at 11:59
  • Thank you so much for the answers, isinstance() function is exactly what I was looking for! Commented Nov 8, 2020 at 12:12

4 Answers 4

1

Use isinstance:

if not isinstance(x, (int, float)) and not isinstance(y, (int, float)):
    # do something..
Sign up to request clarification or add additional context in comments.

Comments

1

Use isinstance

if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):

Comments

0

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')

Comments

0

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)):
    ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.