How can I determine whether user input is EITHER a float or an integer within a loop? If they input something other than integer/float, I want the loop to repeat until they correctly input a float/integer.
Any help is appreciated! :)
How can I determine whether user input is EITHER a float or an integer within a loop? If they input something other than integer/float, I want the loop to repeat until they correctly input a float/integer.
Any help is appreciated! :)
 
    
     
    
    You can use Errors that are being reported when trying to parse incorrect data using float() and int() function.First, define a generic function to parse both int and float and throw some exception in all other cases:
def parse(x):
    value=0
    try:
        value = int(x)
    except ValueError:
        try:
            value = float(x)
        except ValueError:
            raise Exception
    return value
you can use this generic function to determine correct or incorrect input in a loop
correct = False
while not correct:
    try:
        parse(input("Enter data:"))
        correct = True
    except Exception:
        print("Invalid input...enter again!")
