Reputation: 1
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")
Upvotes: 0
Views: 36
Reputation: 91189
Potential problems with using .isdigit()
to validate numeric input are:
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
Upvotes: 0