Home > Blockchain >  How to Check data is int, float in python
How to Check data is int, float in python

Time:03-29

I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python?

However, it does not provide the answer I'm looking for. What I'm trying to do is this:

                            def is_int_or_float(s):
                                try:
                                    a = float(s)
                                    return 1 if s.count('.')==0 else 2
                                except ValueError:
                                    return -1
                            val = input("Enter your value: ")
                            data = is_int_or_float(val) 
                            print(data)

What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this With Exception handling (User Message)

CodePudding user response:

Try this:

def is_int_or_float(value):
    try:
        tmp = float(value)
        return 1 if tmp.is_integer() else 2
    except ValueError:
        return -1

And testing:

>>> is_int_or_float("a")
-1
>>> is_int_or_float("22") 
1
>>> is_int_or_float("22.646") 
2
>>> is_int_or_float("22.64.6") 
-1
>>> is_int_or_float("22.000")  
1
>>> is_int_or_float("1e-4")
2

CodePudding user response:

You can create a simple handle for that.

Check the code. You need to implements you exception handle logic.

class AbstractHandler:
    def is_float(self):
        raise NotImplementedError

    def is_int(self):
        raise NotImplementedError

    def verify(self):
        raise NotImplementedError

class Handler(AbstractHandler):
    def is_float(self, number):
        try:
            float(number)
            return True
        except ValueError:
            # Your exception handler here
            return False

    def is_int(self, number):
        try:
            int(number)
            return True
        except ValueError:
            # Your exception handler here
            return False

    def verify(self, var):
        if self.is_float(var) or self.is_int(var):
            return True
        else:
            return False


def is_number(var):
    """
        Verify if input is a instance of int or float
    Args:
        var (str): input to be verified
    """
    handler = Handler()
    return handler.verify(var)

Some tests:

1 is True
1.1 is True
1.1.1 is False

CodePudding user response:

One way to check, for example integer, use isinstance:

x = 1
if isinstance(x, int):
    # Do something
  • Related