0

I tried using a simple function after asking for a decimal d but realized that the exception is that it didn't catch the difference between 8, and 8.0, and don't really know how to fix it. I tried saving them into strings and comparing them but that didn't work either.

def validdec():
    if d == round(d):
        print("Invalid decimal.")
    else:
        print("Valid Decimal.")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    Does this answer your question? [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – Loïc Feb 28 '22 at 03:23
  • When you say "decimal", what do you mean exactly? Do you mean [`float`](https://docs.python.org/3/library/functions.html#float)? cause that's what `8.0` is, not a [`Decimal`](https://docs.python.org/3/library/decimal.html). Or are you referring to *real* numbers? In that case the [`numbers`](https://docs.python.org/3/library/numbers.html) module might be useful. BTW, welcome to Stack Overflow! Check out [ask] if you want tips. – wjandrea Feb 28 '22 at 03:28

1 Answers1

0

Dunno if this is what you need but you can use the function isinstance to do this.

def validdec(d): 
    if isinstance(d, int): 
        print("Invalid decimal.") 
    else: print("Valid Decimal.")

validdec(1.2)
# Output: Valid decimal.

validdec(1)
# Output: Invalid decimal.

You can also do it like this for a cute looking one-liner:

def validdec(d): print("Invalid decimal.") if isinstance(d, int) else print("Valid Decimal.")

More about isinstance: https://docs.python.org/3/library/functions.html#isinstance

EDIT: As suggested from wjandrea:

def validdec(d): 
    print("Invalid" if isinstance(d, int) else "Valid", "decimal.")
Luka Cerrutti
  • 667
  • 1
  • 4
  • 9
  • 2
    I wouldn't use that one-liner. Shorter is not always better, and in this case it's harder to read. But if you put the `def` on a separate line, it wouldn't be too bad, and you could shorten the conditional: `print("Invalid" if isinstance(d, int) else "Valid", "decimal.")` – wjandrea Feb 28 '22 at 03:35
  • Hmm, that link doesn't mention subclasses at all. I'd avoid W3Schools for Python; it's generally not very good. Instead I recommend [the official docs](https://docs.python.org/3/library/functions.html#isinstance). – wjandrea Feb 28 '22 at 03:40