Ted Idzikowski Ted Idzikowski - 20 days ago 5
Python Question

Handling erroneous user input such as float and number length

I'm trying to handle a user's erroneous input such as floats and integers of length inferior to say 4 and superior to 4 so that whenever it happens, I ask the user to re-enter the 4 digits number.

The expected outcome.

>>> beginning = input('Enter date: ')
>>> Enter date: 1985.0
>>> Please give a four digit integer for date.
>>> Enter date: 19.8
>>> Please give a four digit integer for date.
>>> Enter date: blabla
>>> Please give a four digit integer for date.
>>> Enter date: 200
>>> Please give a four digit integer for date.
>>> Enter date: 20000
>>> Please give a four digit integer for date.
>>> Enter date: 1980
>>> # This is good


Here's my attempt.

def reading_ans():
while True:
try:
ans = input('Enter date: ')
if float(ans) != float(int(float((ans)))):
print("Please give a four digit integer for date.")
elif len(ans) != 4:
print("Please give a four digit integer for date.")
else:
return ans

Answer

I would suggest that your condition use the fact that ans.isdigit() is only True if ans consists solely of digits.

def reading_ans():
    while True:
        ans = input('Enter date: ')
        if len(ans) == 4 and ans.isdigit():
            return ans
        print("Please give a four digit integer for date.")