-2

I want to check the type of input, check if data is float or int.

# type of inData will be String
inData = input("Enter Data")

if inData.isdigit():
    print("Integer")

This will check if the inData is an integer, but this won't check for float type.

Any suggestions?

Ralf
  • 16,086
  • 4
  • 44
  • 68

2 Answers2

2

As I understand it, you want to check whether inData can be converted to float. You can do that like this:

def isFloat(x):
    try:
        float(x) #tries to convert x to float. raises an exception if unsuccessful
    except ValueError:
        return False # return false if exception was raised
    return True

if isFloat(inData):
    print("Float")

For understanding exceptions have a look at this

KJoke
  • 59
  • 6
  • Please do not post answers to duplicate questions. Flag them as duplicate instead (unless someone has already voted to close as a duplicate). – jpmc26 Feb 07 '18 at 00:54
-3

You can use the type() builtin to see the type of an object.

For example, type(inData) is float will return True if inData is a float.

Lee Gaines
  • 484
  • 3
  • 11
  • 2
    inData is already string because of input() method. if you use type(inData) method then it will return string – Shankar Shrestha Feb 06 '18 at 22:51
  • 1
    You want to use `isinstance(inData, float)` for what you are trying to accomplish, which is still wrong because `inData` is a string. https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python – Alexander Feb 06 '18 at 22:54
  • `type(X) is Y` will give you a false negative if `X` is an instance of a subtype of `Y`. Compare `type(True) is int` with `isinstance(True, int)`. – chepner Feb 06 '18 at 23:05
  • let me put it in another way. Is there any similar method similar to isdigit() method..?? – Shankar Shrestha Feb 06 '18 at 23:07
  • Shankar: **No**, there isn't one. – martineau Feb 06 '18 at 23:11