Forcing integer input using the isdigit() method

32 Views Asked by At

Is the following code conventionally acceptable and what are some problems that may arise from implementing the required solution in such a manner?

while True:
    Iq = input("What is your Iq? ")
    if Iq.isdigit():
        print(Iq)
        break
    else:
        print("that is not a number")
1

There are 1 best solutions below

0
dan04 On

Potential problems with using .isdigit() to validate numeric input are:

  • It doesn't handle negative numbers. Sometimes, this is expected behavior. I doubt that any of your users would actually have a negative IQ. However, for questions like “What's the current temperature?” (in winter) or “What's the current balance of your bank account?” (if it's overdrawn), negative numbers could be legal inputs.
  • It doesn't handle floating-point numbers. Again, this could be a desired feature in cases where only whole-number inputs make sense.

Even if you do want to restrict the user to entering positive whole numbers, you might want to have different error messages for negative/non-integer inputs than for completely non-numeric inputs such as abc or the empty string.

Here's a more robust input function, which allows negative or non-integer inputs, and also supports optional bounds-checking for the value.

def input_int(prompt='', lo_value=None, hi_value=None):
    while True:
        # Have the user input a string.
        entry = input(prompt)
        # Try to parse the string as a number.
        try:
            value = int(entry)
        except ValueError:
            # If they entered a float, round it to an int.
            try:
                value = round(float(entry))
            except ValueError:
                print('That is not a number.')
                continue
        # Bounds check the value.
        if (lo_value is not None) and (value < lo_value):
            print(f'Value cannot be less than {lo_value}.')
        elif (hi_value is not None) and (value > hi_value):
            print(f'Value cannot be more than {hi_value}.')
        else:
            return value