0

I am constructing a basic function with an if statement based on datatype. I am wondering whether there is any problem with using:

if type(number) == int:

in something like:

def distance_from_zero(number):
"""Takes input 'number', checks datatype. If integer or floating point, returns absolute value. If other, returns 'Nope'"""
if type(number) == int:
    return abs(number)
elif type(number) == float:
    return abs(number)
else:
    return "Nope"

distance_from_zero(45)

Is there a cleaner/better way to use datatypes in if statements?

Andy G
  • 18,518
  • 5
  • 42
  • 63
macnsteeeze
  • 61
  • 1
  • 1
  • 4

3 Answers3

4

Why even check?

try:
    return abs(number)
except TypeError:
    return 'Nope'
kylieCatt
  • 9,293
  • 4
  • 39
  • 50
2

You can use isinstance()

if isinstance(number, (int, float)):
    return abs(number)
Valentin Briukhanov
  • 1,103
  • 8
  • 13
1

I don't see any problem with that code, although you can write it more simply as:

if type(number) in (int, float):
    return abs(number)
else:
    return "Nope"
Andy G
  • 18,518
  • 5
  • 42
  • 63