python - Why does my function return None? -
this may easy question answer, can't simple program work , it's driving me crazy. have piece of code:
def dat_function(): my_var = raw_input("type \"a\" or \"b\": ") if my_var != "a" , 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 input "a" or "b",everything fine. output is:
type "a" or "b": a -from dat_function -from main() but, if type else , "a" or "b", this:
type "a" or "b": purple didn't type "a" or "b". try again. type "a" or "b": a -from dat_function none -from main() i don't know why dat_function() returning none, since should return my_var. print statement shows my_var correct value, function doesn't return value reason.
it returning none because when recursively call it:
if my_var != "a" , my_var != "b": print "you didn't type \"a\" or \"b\". try again." print " " dat_function() ..you don't return value.
so while recursion happen, return value gets discarded, , fall off end of function. falling off end of function means python implicitly returns none, this:
>>> def f(x): ... pass >>> print(f(20)) none so, instead of calling dat function() in if statement, need return it.
Comments
Post a Comment