Why does my function return None?

2018-12-31 01:36发布

This may be an easy question to answer, but I can't get this simple program to work and it's driving me crazy. I have this piece of code:

def Dat_Function():
    my_var = raw_input("Type \"a\" or \"b\": ")

    if my_var != "a" and my_var != "b":
        print  "You didn't type \"a\" or \"b\".  Try again."
        print " "
        Dat_Function()
    else:
        print my_var, "-from Dat_Function"
        return my_var


def main():
    print Dat_Function(), "-From main()"

main()

Now, if I input just "a" or "b",everything is fine. The output is:

Type "a" or "b": a
a -from Dat_Function
a -From main()

But, if I type something else and then "a" or "b", I get this:

Type "a" or "b": purple
You didn't type "a" or "b".  Try again.

Type "a" or "b": a
a -from Dat_Function
None -From main()

I don't know why Dat_Function() is returning None, since it should only return my_var. The print statement shows that my_var is the correct value, but the function doesn't return that value for some reason.

4条回答
柔情千种
2楼-- · 2018-12-31 02:05

It is returning None because when you recursively call it:

if my_var != "a" and my_var != "b":
    print  "You didn't type \"a\" or \"b\".  Try again."
    print " "
    Dat_Function()

..you don't return the value.

So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns None, just like this:

>>> def f(x):
...     pass
>>> print(f(20))
None

So, instead of just calling Dat Function() in your if statement, you need to return it.

查看更多
栀子花@的思念
3楼-- · 2018-12-31 02:14

To return a value other than None, you need to use a return statement.

In your case, the if block only executes a return when executing one branch. Either move the return outside of the if/else block, or have returns in both options.

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 02:14
def Dat_Function():
    my_var = raw_input("Type \"a\" or \"b\": ")

    if my_var != "a" and my_var != "b":
        print  "You didn't type \"a\" or \"b\".  Try again."
        print " "
        return Dat_Function()
    else:
        print my_var, "-from Dat_Function"
        return my_var


def main():
    print Dat_Function(), "-From main()"

main()
查看更多
步步皆殇っ
5楼-- · 2018-12-31 02:26

I think that you should use while loops.

if my_var != "a" and my_var != "b": print "You didn't type \"a\" or \"b\". Try again." print " " return Dat_Function()

Consider that you type something different than "a" and "b", of course, it will call Dat_Function but then it is skipping the next part. Which is:

else: print my_var, "-from Dat_Function" return my_var

And will go directly into:

def main(): print Dat_Function(), "-From main()"

So, if you use while loop as:

while my_var!="a" and my_var!="b": print ('you didn't type a or b') return Dat_Function()

This way I think that you can handle it.

查看更多
登录 后发表回答