-1

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! :)

Rich Benner
  • 7,873
  • 9
  • 33
  • 39
Kody
  • 17
  • 1
  • 3
  • 1
    "while userInputNotSatisfied:" see http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – frank Jun 29 '16 at 06:44

1 Answers1

-1

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!")