Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't know how to distinguish between an integer and a decimal

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading