处理错误的用户输入,例如浮点数和数字长度

时间:2016-11-20 05:48:42

标签: python python-3.x

我正在尝试处理用户的错误输入,例如浮点数和长度低于4且高于4的整数,这样无论何时发生,我都要求用户重新输入4位数。

预期结果。

>>> 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

这是我的尝试。

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

1 个答案:

答案 0 :(得分:0)

如果ans.isdigit()仅由数字组成,我建议您的条件使用Trueans的事实。

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