Home > Back-end >  how can I raise an error if user input is a float - Python
how can I raise an error if user input is a float - Python

Time:03-23

I am trying to write a function that checks whether the inputs are a float (decimal) and if so raises an error and returns a messagebox. below are the first two functions, for reference purposed, which preceed the troublesome validate_float().

def validate_integer():
    """Returns error message if input is not an integer"""
    while True:
        try: 
            i.get() == int or j.get() == int
        except Exception:
            return messagebox.showerror('Input Error', 'Input must be integer!')
        else:
            validate_positive_integer()
            break

def validate_positive_integer():
    """Returns error message if input integer is negative"""
    while True:
        if i.get() <= 1 or j.get() <= 1:
            return messagebox.showerror('Input Error', 'Row number input must be greater than 1')
        else:
            validate_float()
            break

The above functions work as intended when it comes to validate_float(), it calls main_function even if the input is a float (eg. 3.4, 6.7, 9.99999 etc). here it is below

def validate_float():
    """Returns error message if input is float"""
    while True:
        if float(i.get()) or float(j.get()):
            return messagebox.showerror('Input Error', 'Row number input cannot be float')
        else:
            main_function()

I just don't want the user to be able to input a float, I've tried a few different ways to get this function to walk, none of which have been 100% to my desired outcome.

CodePudding user response:

Have you tried with the native python function isinstance()?

Here's an example:

isinstance(1, float) ➔ false
isinstance(0.0, float) ➔ true

Note that when you use float(x) it is just converting x into a float. It will raise OverflowError if you pass a non-convertible value as input (e.g. "hello"), but this cannot be considered to be a proper check.

CodePudding user response:

Your validate_float() function should be as:

def validate_float():
    """Returns error message if input is float"""
    while True:
        if i.get()== float or j.get()== float:
            return messagebox.showerror('Input Error', 'Row number input cannot be float')
        else:
            main_function()
  • Related