Python代码返回“ NoneType”而不是“ int”

时间:2018-08-05 09:38:35

标签: python int nonetype

对不起,我是一个完整的初学者,昨天才刚开始。

我对以下代码有疑问。因此,只要输入一个数字,它就可以正常工作,并且将返回为“ int”(这就是我需要的)。但是,如果我输入其他任何东西再次触发number_validation()函数,它将返回为“ NoneType”。知道为什么我做错了什么吗?

感谢您的帮助!

def number_validation():
    number = input("Please enter a number: ")
    if number == "":
        print("You need to enter a number")
        number_validation()
    elif number != "":
        if number.isdigit() == True:
            number = int(number)
            return number
        else:
            print("Numbers only, no spaces, please try again!")
            number_validation()

1 个答案:

答案 0 :(得分:1)

那是因为您第二次打电话时return不是number_validation

In [210]: def number_validation():
     ...:     number = input("Please enter a number: ")
     ...:     if number == "":
     ...:         print("You need to enter a number")
     ...:         number_validation()
     ...:     elif number != "":
     ...:         if number.isdigit() == True:
     ...:             number = int(number)
     ...:             return number
     ...:         else:
     ...:             print("Numbers only, no spaces, please try again!")
     ...:             return number_validation()      # Note the return here
     ...:

In [211]: number_validation()
Please enter a number: a
Numbers only, no spaces, please try again!
Please enter a number: 10
Out[211]: 10

使用原始代码,您将到达函数的末尾而不返回任何内容,因此Python将隐式返回一个None