检查来自用户的输入是否为有效数字

时间:2018-09-07 16:43:44

标签: python python-3.x

在下面的代码中,我试图检查输入的数字只是一个整数,并且不小于1。如果我首先输入负数作为验证的输入,然后输入正确的值,则它不返回值

输出1:

Enter the No of fruits:text
text is not an integer.
Enter the No of fruits:-1
Enter a valid number
Enter the No of fruits:5
Outside while
Outside while

输出2:

Enter the No of fruits:text
text is not an integer.
Enter the No of fruits:5
Outside while
Enter the fruit Type:

代码:

def getNoOfFruits():
    count = 0
    while count is 0:
        inputnum = input("Enter the No of fruits:")
        try:
            count =int(inputnum )
        except ValueError:
            print("%s is not an integer.\n" % inputnum )
            continue
        if count < 1:
            print("Enter a valid number")
            getNoOfFruits()
        else:
            break
    print("Outside while")
    return count

No_Of_Fruits = getNoOfFruits()
type = input("Enter the fruit Type:")

0 个答案:

没有答案