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

Making a program that determines the data type: How do I change the type of data I input?

I’m making a program that determines what type the input is (int, float or str), however I know that the input() function accepts inputs as strings so I’m a bit stuck.

stuff = input('Enter something: ')
print('Input is int?', stuff == int(stuff))
print('Input is float?', stuff == float(stuff))
print('Input is string?', stuff == str(stuff))

The above code is just to provide some context, it doesn’t actually work though.

Or the more practical way:

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

stuff = input('Enter something: ')
print(type(stuff))

But it always returns <class 'str'> which doesn’t always provide the correct answer e.g what if I entered "10"? Any ideas on how to change the type the input?

>Solution :

Do something like this:

stuff = input('Enter something: ')
try:
    # first you try an int, which is the most restrictive one
    stuff = int(stuff)
    print("It's an int")
except ValueError:
    # then you try a float which is less restrictive
    try: 
        stuff = float(stuff)
        print("It's a float")
    except ValueError:
        # if both conversions fail, it's a string
        print("Looks like it's a string after all")
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