Search code examples
pythonpython-3.xalgorithmpython-2.7

How to check every data type from input in python?


Simple, I want to check the data type like string, integer or *any other type* which is input. We don't know the type and if it's a number I need to get its absolute value. However, if it's another type, I have other actions for each data type. For example, if it's a string print string or if it's a float print float like that. How can I solve this problem in a simple way?

Before asking this question, I've tried:

def mainDataFunc():
    x = input("Anything: ")
    try:
        if type(abs(x)) is int:
            print("This is integer.")
        elif type(abs(x)) is float:
            print("This is float.")
        elif type(x) is str:
            print("This is string.")
    except ValueError:
        print("Type is not valid.")

Solution

  • This should work

    user_input = input("Enter something ")
    
    try:
        val = int(user_input)
        print("Input is an integer")
    except ValueError:
        try:
            val = float(user_input)
            print("Input is a float")
        except ValueError:
            print("It's a string")