函数返回" NoneType"在错误检查一个输入之后,但在另一个输入中没有

时间:2016-12-30 16:53:56

标签: python python-3.x

两个函数使用相同的check(x)函数,并且几乎相同,除了第二个函数必须采用的参数才能使用print

输入int作为输入显示没有问题。

但是,如果输入了字母,则enter_num()的返回结果将变为NoneType,但这不会发生在enter_amount()中。

哪里以及如何出错?

def check(x):                           #check if user input is integer
    try:
        int(x)
        return True
    except ValueError:
        return False

def enter_num():                        #get user input for lotto numbers
    x = input("buy num:")
    if check(x) == True:                #check int
        x = int(x)
        return x                        
    else:
        print("Please enter integer")
        enter_num()

def enter_amount(x):                    #get user amount of the lottos
    print(x)                          ##if enter_num errored once, this will show None##
    y = input("How many?")
    if check(y) == True:                #check int
        y = int(y)
        print("%s for %s copies" % (x,y))
        return y
    else:
        print("Please enter integer")
        enter_amount(x)                 

buy_num = enter_num()
amount = enter_amount(buy_num)

1 个答案:

答案 0 :(得分:6)

您永远不会从enter_num()返回递归结果:

def enter_num():
    x = input("buy num:")
    if check(x) == True:
        x = int(x)
        return x                        
    else:
        print("Please enter integer")
        enter_num()  # ignoring the return value
    # so None is returned instead

同样适用于enter_amount();它忽略了递归调用。

您需要显式返回递归调用结果,就像您对任何其他表达式一样:

def enter_num():
    x = input("buy num:")
    if check(x) == True:
        x = int(x)
        return x                        
    else:
        print("Please enter integer")
        return enter_num()  # ignoring the return value

enter_amount()执行相同操作;将最后一行更改为return enter_amount(x)

但你真的不应该使用递归;用户所要做的就是按住ENTER键一小段时间,以便代码最终打破递归限制。有关更好的技巧,请参阅Asking the user for input until they give a valid response;这里有一个while循环。

也无需测试== True; if 已经测试真相:

if check(x):

我还要内联check测试;如果可以转换字符串,则无需转换为int() 两次。以下内容不会用完递归深度,但如果int(x)包含可转换值,则直接返回x,否则会打印错误消息,然后再循环返回以再次询问该数字:

def enter_num():
    while True:
        x = input("buy num:")
        try:
            return int(x)
        except ValueError:
            print("Please enter integer")