Cate Cate - 1 month ago 7
Python Question

Why does my function return None?

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.

Answer

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.