Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my recursive function return None?

I have this function that calls itself:

def get_input():     my_var = input('Enter "a" or "b": ')      if my_var != "a" and my_var != "b":         print('You didn\'t type "a" or "b". Try again.')         get_input()     else:         return my_var  print('got input:', get_input()) 

Now, if I input just "a" or "b", everything works fine:

Type "a" or "b": a got input: a 

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 got input: None 

I don't know why get_input() is returning None since it should only return my_var. Where is this None coming from and how do I fix my function?

like image 571
Cate Avatar asked Jul 22 '13 00:07

Cate


People also ask

Why does my function keep returning None?

If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.

Does a recursive function always return a value?

All functions - recursive or not - have one or more return . The return may or may not include a value. It is for you to decide when you write the function. All explicit written return statements must return the correct type.

What happens if there is no base case in recursion?

If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.


2 Answers

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.')     get_input() 

..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 get_input() in your if statement, you need to return it:

if my_var != "a" and my_var != "b":     print('You didn\'t type "a" or "b". Try again.')     return get_input() 
like image 110
roippi Avatar answered Sep 19 '22 08:09

roippi


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.

like image 40
Simon Avatar answered Sep 22 '22 08:09

Simon