Search code examples
python-3.xtypesuser-input

How to get the type of an object which data has passed by user


I taking input from user in python, How to know user has passed int or string or float etc??

number1 = eval(sys.argv[1])
number2 = eval(sys.argv[2])

if user passed input is float or int, i want to sum them, but how to know which type of data user passed? because all data which user passes is default type is string.


Solution

  • We can use eval() for that,

    import sys
    
    
    def main():
        number1 = eval(sys.argv[1])
        number2 = eval(sys.argv[2])
        print(number1 + number2)
    
    
    if __name__ == '__main__':
        main()
    

    when the user enters an integer as an input the input() function returns a string, but in the case of eval() it will evaluate the returned value from a string to an integer, same in float . No need to check data type every time.

    see 3rd number of below link,

    https://towardsdatascience.com/python-eval-built-in-function-601f87db191