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

Python Check only outputting a string

num = input("Enter Something:")
    print(type(num))

for some reason when running this code, or any alternative version even without text (string), it still outputs a string.

<class 'str'>

is there any way to check for all types like expected? e.g str and int

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

>Solution :

The problem is that input() returns a string, so the datatype of num will always be a string. If you want to look at that string and determine whether it’s a string, int, or float, you can try converting the string to those datatypes explicitly and check for errors.

Here’s an example of one such check:

def check_user_input(input):
try:
    # Convert it into integer
    val = int(input)
    print("Input is an integer number. Number = ", val)
except ValueError:
    try:
        # Convert it into float
        val = float(input)
        print("Input is a float  number. Number = ", val)
    except ValueError:
        print("No.. input is not a number. It's a string")

I got this example here where there’s a more thorough explanation: https://pynative.com/python-check-user-input-is-number-or-string/

Here is a solution based on that for your problem specifically:

def convert_input(input):
    try:
        # Convert it into integer
        val = int(input)
        return val
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            return val
        except ValueError:
            return input

num = input("Enter Something:")
num = convert_input(num)
print(type(num))
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